Advertisement
Kirafon

test Car

Mar 23rd, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.66 KB | None | 0 0
  1. package com.example.cartouch;
  2.  
  3. import android.app.Activity;
  4. import android.bluetooth.BluetoothAdapter;
  5. import android.bluetooth.BluetoothDevice;
  6. import android.bluetooth.BluetoothSocket;
  7. import android.content.Intent;
  8. import android.os.Bundle;
  9. import android.os.Handler;
  10. import android.util.Log;
  11. import android.view.MotionEvent;
  12. import android.view.View;
  13. import android.view.View.OnTouchListener;
  14. import android.widget.TextView;
  15. import android.widget.Toast;
  16.  
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.util.UUID;
  21.  
  22.  
  23. public class MainActivity extends Activity implements OnTouchListener {
  24.  
  25.     private static final int REQUEST_ENABLE_BT = 1;
  26.     final int ArduinoData = 1;
  27.     final String LOG_TAG = "MyLogs";
  28.     private BluetoothAdapter btAdapter = null;
  29.     private BluetoothSocket btSocket = null;
  30.     private static String MacAddress = "20:16:06:28:19:52";
  31.     private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  32.     private ConnectedThred MyThred = null;
  33.     public TextView point;
  34.  
  35.     Handler h;
  36.     private StringBuilder sb = new StringBuilder();
  37.     private static final String TAG = "bluetooth2";
  38.  
  39.  
  40.     int x;
  41.     int y;
  42.     int xi;
  43.     int yi;
  44.     int xii;
  45.     int yii;
  46.     String sDown;
  47.     String sMove;
  48.     String sUp;
  49.     String sCar;
  50.  
  51.  
  52.     @Override
  53.     public void onCreate(Bundle savedInstanceState) {
  54.         super.onCreate(savedInstanceState);
  55.         setContentView(R.layout.activity_main);
  56.  
  57.         btAdapter = BluetoothAdapter.getDefaultAdapter();
  58.         point = (TextView) findViewById(R.id.textView);
  59.  
  60.         if (btAdapter != null){
  61.             if (btAdapter.isEnabled()){
  62.                 point.setText("Bluetooth включен. Все отлично.");
  63.             }else
  64.             {
  65.                 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  66.                 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  67.             }
  68.  
  69.         }else
  70.         {
  71.             MyError("Fatal Error", "Bluetooth ОТСУТСТВУЕТ");
  72.         }
  73.  
  74.  
  75.         point = new TextView(this);
  76.         point.setOnTouchListener(this);
  77.         setContentView(point);
  78.  
  79.         h = new Handler() {
  80.             public void handleMessage(android.os.Message msg) {
  81.                 switch (msg.what) {
  82.                     case ArduinoData:
  83.                         byte[] readBuf = (byte[]) msg.obj;
  84.                         String strIncom = new String(readBuf, 0, msg.arg1);
  85.                         sb.append(strIncom);// формируем строку
  86.                         int beginOfLineIndex = sb.indexOf("*");//определяем символы начала строки
  87.                         int endOfLineIndex = sb.indexOf("#");//определяем символы конца строки
  88.                         //Если блок данных соотвествует маске *данные# то выполняем код
  89.                         if ((endOfLineIndex > 0) && (beginOfLineIndex == 0)) {                                            // если встречаем конец строки,
  90.                             String sbprint = sb.substring(beginOfLineIndex+1, endOfLineIndex-3);               // то извлекаем строку
  91.                             point.setText("Данные от Arduino: " + sbprint);
  92.  
  93.                         }
  94.                         sb.delete(0, sb.length());
  95.                         break;
  96.                 }
  97.             };
  98.         };
  99.  
  100.     }
  101.  
  102.  
  103.     @Override
  104.     public boolean onTouch(View v, MotionEvent event) {
  105.  
  106.  
  107.         int x = (int) event.getX();
  108.         int y = (int) event.getY();
  109.  
  110.         switch (event.getAction()) {
  111.             case MotionEvent.ACTION_DOWN: // нажатие
  112.                 sDown = "Down: " + x + "," + y;
  113.                 sMove = "";
  114.                 sUp = "";
  115.                 xi = x;
  116.                 xii = 0;
  117.                 yi = y;
  118.                 yii = 0;
  119.                 break;
  120.             case MotionEvent.ACTION_MOVE: // движение
  121.                 sMove = "Move: " + (x - xi) + "," + (yi - y);
  122.                 xii = x - xi;
  123.                 yii = y - yi;
  124.                 sCar = xii + ":" + yii;
  125.                 break;
  126.             case MotionEvent.ACTION_UP: // отпускание
  127.             case MotionEvent.ACTION_CANCEL:
  128.                 sMove = "";
  129.                 sUp = "Up: " + (x - xi) + "," + (yi - y);
  130.                 xii = 0;
  131.                 yii = 0;
  132.                 sCar = xii + ":" + yii;
  133.                 break;
  134.         }
  135.         point.setText(sDown + "\n" + sMove + "\n" + sUp);
  136.         MyThred.sendData("5");
  137.         return true;
  138.     }
  139.  
  140.  
  141.     @Override
  142.     public void onResume() {
  143.         super.onResume();
  144.         if (btAdapter != null){
  145.             if (btAdapter.isEnabled()){
  146.                 BluetoothDevice device = btAdapter.getRemoteDevice(MacAddress);
  147.                 Log.d(LOG_TAG, "***Получили удаленный Device***"+device.getName());
  148.  
  149.                 try {
  150.                     btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  151.                     Log.d(LOG_TAG, "...Создали сокет...");
  152.                 } catch (IOException e) {
  153.                     MyError("Fatal Error", "В onResume() Не могу создать сокет: " + e.getMessage() + ".");
  154.                 }
  155.  
  156.                 btAdapter.cancelDiscovery();
  157.                 Log.d(LOG_TAG, "***Отменили поиск других устройств***");
  158.  
  159.                 Log.d(LOG_TAG, "***Соединяемся...***");
  160.                 try {
  161.                     btSocket.connect();
  162.                     Log.d(LOG_TAG, "***Соединение успешно установлено***");
  163.                 } catch (IOException e) {
  164.                     try {
  165.                         btSocket.close();
  166.                     } catch (IOException e2) {
  167.                         MyError("Fatal Error", "В onResume() не могу закрыть сокет" + e2.getMessage() + ".");
  168.                     }
  169.                 }
  170.  
  171.                 MyThred = new ConnectedThred(btSocket);
  172.                 MyThred.start();
  173.             }
  174.         }
  175.     }
  176.  
  177.     @Override
  178.     public void onPause() {
  179.         super.onPause();
  180.  
  181.         Log.d(LOG_TAG, "...In onPause()...");
  182.  
  183.         if (btAdapter != null){
  184.             if (btAdapter.isEnabled()){
  185.                 if (MyThred.status_OutStream() != null) {
  186.                     MyThred.cancel();
  187.                 }
  188.                 try     {
  189.                     btSocket.close();
  190.                 } catch (IOException e2) {
  191.                     MyError("Fatal Error", "В onPause() Не могу закрыть сокет" + e2.getMessage() + ".");
  192.                 }
  193.             }
  194.         }
  195.     }//OnPause
  196.  
  197.     private void MyError(String title, String message){
  198.         Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
  199.         finish();
  200.     }
  201.  
  202.  
  203.     //Отдельный поток для передачи данных
  204.     private class ConnectedThred extends Thread{
  205.         private final BluetoothSocket copyBtSocket;
  206.         private final OutputStream OutStream;
  207.         private final InputStream InStream;
  208.  
  209.         public ConnectedThred(BluetoothSocket socket){
  210.             copyBtSocket = socket;
  211.             OutputStream tmpOut = null;
  212.             InputStream tmpIn = null;
  213.             try{
  214.                 tmpOut = socket.getOutputStream();
  215.                 tmpIn = socket.getInputStream();
  216.             } catch (IOException e){}
  217.  
  218.             OutStream = tmpOut;
  219.             InStream = tmpIn;
  220.         }
  221.  
  222.         public void run()
  223.         {
  224.             btAdapter.cancelDiscovery();
  225.             byte[] buffer = new byte[1024];
  226.             int bytes;
  227.  
  228.             while(true){
  229.                 try{
  230.                     bytes = InStream.read(buffer);
  231.                     h.obtainMessage(ArduinoData, bytes, -1, buffer).sendToTarget();
  232.                 }catch(IOException e){break;}
  233.  
  234.             }
  235.  
  236.         }
  237.  
  238.         public void sendData(String message) {
  239.             byte[] msgBuffer = message.getBytes();
  240.             Log.d(LOG_TAG, "***Отправляем данные: " + message + "***"  );
  241.  
  242.             try {
  243.                 OutStream.write(msgBuffer);
  244.             } catch (IOException e) {}
  245.         }
  246.  
  247.         public void cancel(){
  248.             try {
  249.                 copyBtSocket.close();
  250.             }catch(IOException e){}
  251.         }
  252.  
  253.         public Object status_OutStream(){
  254.             if (OutStream == null){return null;
  255.             }else{return OutStream;}
  256.         }
  257.     }
  258. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement