Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.68 KB | None | 0 0
  1. package com.projekttest.gospodin.bluetooth_rc_auto.Akcelerometar;
  2.  
  3. import android.bluetooth.BluetoothAdapter;
  4. import android.bluetooth.BluetoothDevice;
  5. import android.bluetooth.BluetoothSocket;
  6. import android.content.Context;
  7. import android.hardware.Sensor;
  8. import android.hardware.SensorEvent;
  9. import android.hardware.SensorEventListener;
  10. import android.hardware.SensorManager;
  11. import android.os.Build;
  12. import android.os.Bundle;
  13. import android.os.Handler;
  14. import android.os.HandlerThread;
  15. import android.support.v7.app.AppCompatActivity;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.view.WindowManager;
  19. import android.widget.Button;
  20. import android.widget.TextView;
  21.  
  22. import com.projekttest.gospodin.bluetooth_rc_auto.R;
  23.  
  24. import java.io.IOException;
  25. import java.io.InputStream;
  26. import java.io.OutputStream;
  27. import java.lang.reflect.Method;
  28. import java.util.UUID;
  29.  
  30. public class Akcelerometar_Activity extends AppCompatActivity {
  31.     private TextView textX, textY, textZ;
  32.     private Button btnF, btnB, btnL, btnR, btnDis;
  33.     private BluetoothAdapter btAdapter2 = null;
  34.     private BluetoothDevice btDevice2 = null;
  35.     private NativeBluetoothSocket btSocket2 = null;
  36.     private boolean isConnected = false;
  37.     private static final UUID DEFAULT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  38.     private String mac_adr = null;
  39.     private boolean secure;
  40.                                                                                 //////////////////                  NOVI SENSOREVENTLISTENER U THREADU
  41.  
  42.     @Override
  43.     protected void onCreate(Bundle savedInstanceState) {
  44.         super.onCreate(savedInstanceState);
  45.         setContentView(R.layout.activity_akcelerometar);
  46.  
  47.         textX = (TextView) findViewById(R.id.textX);
  48.         textY = (TextView) findViewById(R.id.textY);
  49.         textZ = (TextView) findViewById(R.id.textZ);
  50.  
  51.  
  52.         btnF = (Button) findViewById(R.id.btnF);
  53.         btnB = (Button) findViewById(R.id.btnB);
  54.         btnL = (Button) findViewById(R.id.btnL);
  55.         btnR = (Button) findViewById(R.id.btnR);
  56.         btnDis= (Button) findViewById(R.id.btnDis);
  57.  
  58.         mac_adr = getIntent().getStringExtra("MACadr");
  59.         Log.d("MACadresa",""+mac_adr);
  60.  
  61.         btAdapter2 = BluetoothAdapter.getDefaultAdapter();
  62.         btDevice2 = btAdapter2.getRemoteDevice(mac_adr);
  63.  
  64.         Log.d("BLUETOOTHDEVICE","Uređaj: "+btDevice2+"\tAdapter: "+btAdapter2);
  65.         ConnectThread thr = new ConnectThread(btDevice2, btAdapter2);
  66.             thr.start();
  67.  
  68.  
  69.  
  70.         btnDis.setOnClickListener(new View.OnClickListener() {
  71.             public void onClick(View v) {
  72.                 if(btSocket2 != null){
  73.                     try {
  74.                         btSocket2.close();
  75.                         Log.d("Disconnect","Disconnected");
  76.                     } catch (IOException e) {
  77.                         e.printStackTrace();
  78.                     }
  79.                 }
  80.             }
  81.         });
  82.  
  83.  
  84.     }
  85.  
  86.  
  87.  
  88.     private class ConnectThread extends Thread {
  89.  
  90.         private final BluetoothDevice bTDevice;
  91.         private final BluetoothSocket btSocket;
  92.         private final BluetoothAdapter btAdapter;
  93.  
  94.  
  95.         public ConnectThread(BluetoothDevice bTDevice1, BluetoothAdapter adapter) {
  96.             BluetoothSocket tmp = null;
  97.  
  98.             bTDevice = bTDevice1;
  99.             btAdapter = adapter;
  100.  
  101.             try {
  102.                 tmp = createBluetoothSocket(bTDevice);
  103.                 Log.e("KONEKCIJA", "Socket's create() SUCCESS");
  104.  
  105.             } catch (IOException e) {
  106.                 Log.e("KONEKCIJA", "Socket's create() method failed", e);
  107.             }
  108.             btSocket = tmp;
  109.  
  110.         }
  111.  
  112.         public void run() {
  113.  
  114.             btAdapter.cancelDiscovery();
  115.  
  116.             try {
  117.                 Thread.sleep(1000);
  118.                     connect();          /////////   funkcija koja pokrece sve ostale ispod
  119.                 if(btSocket != null){
  120.                     isConnected = true;
  121.  
  122.                         try {
  123.                             Thread_slanje thr_slanje = new Thread_slanje(Akcelerometar_Activity.this.getApplicationContext());
  124.                             thr_slanje.start();
  125.                             Log.d("THREAD_SLANJE", "Start");
  126.  
  127.                         } catch (Exception e) {
  128.                             Log.d("THREAD_SLANJE", "Error");
  129.                         }
  130.  
  131.                 }
  132.                 Log.d("BTdevice: ", "Connected");
  133.             } catch (IOException e) {
  134.                 e.printStackTrace();
  135.                 try {
  136.                     btSocket.close();
  137.                     Log.d("BTSOCKET: ", "CLOSED");
  138.  
  139.                 } catch (IOException e1) {
  140.                     Log.d("BTdevice", "Could not close the client socket");
  141.  
  142.                 }
  143.             } catch (InterruptedException e) {
  144.                 e.printStackTrace();
  145.                 Log.d("THREAD", "INTERRUPTED");
  146.             }
  147.  
  148.  
  149.  
  150.  
  151.  
  152.         }
  153.  
  154.  
  155.  
  156.     }
  157.  
  158.  
  159.  
  160.  
  161.  
  162.  
  163.     private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
  164.         if(Build.VERSION.SDK_INT >= 10){
  165.             try {
  166.                 final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
  167.                 return (BluetoothSocket) m.invoke(device, DEFAULT_UUID);
  168.             } catch (Exception e) {
  169.                 Log.e("CREATE_BT_SOCKET", "Could not create Insecure RFComm Connection",e);
  170.             }
  171.         }
  172.         return  device.createRfcommSocketToServiceRecord(DEFAULT_UUID);
  173.     }
  174.  
  175.     public NativeBluetoothSocket connect() throws IOException {
  176.         boolean success = false;
  177.         while (selectSocket()) {
  178.             btAdapter2.cancelDiscovery();
  179.  
  180.             try {
  181.                 btSocket2.connect();
  182.                 success = true;
  183.                 break;
  184.             } catch (IOException e) {
  185.                 //fallback
  186.                 try {
  187.                     btSocket2 = new FallbackBluetoothSocket(btSocket2.getUnderlyingSocket());
  188.                     Thread.sleep(500);
  189.                     btSocket2.connect();
  190.                     success = true;
  191.                     break;
  192.                 } catch (FallbackException e1) {
  193.                     Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
  194.                 } catch (InterruptedException e1) {
  195.                     Log.w("BT", e1.getMessage(), e1);
  196.                 } catch (IOException e1) {
  197.                     Log.w("BT", "Fallback failed. Cancelling.", e1);
  198.                 }
  199.             }
  200.         }
  201.  
  202.         if (!success) {
  203.             throw new IOException("Could not connect to device: "+ btDevice2.getAddress());
  204.         }
  205.  
  206.         return btSocket2;
  207.     }
  208.  
  209.     private boolean selectSocket() throws IOException {
  210.  
  211.         BluetoothSocket tmp;
  212.  
  213.  
  214.         Log.i("BT", "Attempting to connect to Protocol: "+ DEFAULT_UUID);
  215.         if (secure) {
  216.             tmp = btDevice2.createRfcommSocketToServiceRecord(DEFAULT_UUID);
  217.         } else {
  218.             tmp = btDevice2.createInsecureRfcommSocketToServiceRecord(DEFAULT_UUID);
  219.         }
  220.         btSocket2 = new NativeBluetoothSocket(tmp);
  221.  
  222.         return true;
  223.     }
  224.  
  225.     public static interface BluetoothSocketWrapper {
  226.  
  227.         InputStream getInputStream() throws IOException;
  228.  
  229.         OutputStream getOutputStream() throws IOException;
  230.  
  231.         String getRemoteDeviceName();
  232.  
  233.         void connect() throws IOException;
  234.  
  235.         String getRemoteDeviceAddress();
  236.  
  237.         void close() throws IOException;
  238.  
  239.         BluetoothSocket getUnderlyingSocket();
  240.  
  241.     }
  242.  
  243.     public class NativeBluetoothSocket implements BluetoothSocketWrapper {
  244.  
  245.         private BluetoothSocket socket;
  246.  
  247.         public NativeBluetoothSocket(BluetoothSocket tmp) {
  248.             this.socket = tmp;
  249.         }
  250.  
  251.         @Override
  252.         public InputStream getInputStream() throws IOException {
  253.             return socket.getInputStream();
  254.         }
  255.  
  256.         @Override
  257.         public OutputStream getOutputStream() throws IOException {
  258.             return socket.getOutputStream();
  259.         }
  260.  
  261.         @Override
  262.         public String getRemoteDeviceName() {
  263.             return socket.getRemoteDevice().getName();
  264.         }
  265.  
  266.         @Override
  267.         public void connect() throws IOException {
  268.             socket.connect();
  269.         }
  270.  
  271.         @Override
  272.         public String getRemoteDeviceAddress() {
  273.             return socket.getRemoteDevice().getAddress();
  274.         }
  275.  
  276.         @Override
  277.         public void close() throws IOException {
  278.             socket.close();
  279.         }
  280.  
  281.         @Override
  282.         public BluetoothSocket getUnderlyingSocket() {
  283.             return socket;
  284.         }
  285.  
  286.     }
  287.  
  288.     public class FallbackBluetoothSocket extends NativeBluetoothSocket {
  289.  
  290.         private BluetoothSocket fallbackSocket;
  291.  
  292.         public FallbackBluetoothSocket(BluetoothSocket tmp) throws FallbackException {
  293.             super(tmp);
  294.             try
  295.             {
  296.                 Class<?> clazz = tmp.getRemoteDevice().getClass();
  297.                 Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
  298.                 Method m = clazz.getMethod("createRfcommSocket", paramTypes);
  299.                 Object[] params = new Object[] {Integer.valueOf(1)};
  300.                 fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
  301.             }
  302.             catch (Exception e)
  303.             {
  304.                 throw new FallbackException(e);
  305.             }
  306.         }
  307.  
  308.         @Override
  309.         public InputStream getInputStream() throws IOException {
  310.             return fallbackSocket.getInputStream();
  311.         }
  312.  
  313.         @Override
  314.         public OutputStream getOutputStream() throws IOException {
  315.             return fallbackSocket.getOutputStream();
  316.         }
  317.  
  318.  
  319.         @Override
  320.         public void connect() throws IOException {
  321.             fallbackSocket.connect();
  322.         }
  323.  
  324.  
  325.         @Override
  326.         public void close() throws IOException {
  327.             fallbackSocket.close();
  328.         }
  329.  
  330.     }
  331.  
  332.     public static class FallbackException extends Exception {
  333.  
  334.         private static final long serialVersionUID = 1L;
  335.  
  336.         public FallbackException(Exception e) {
  337.  
  338.             super(e);
  339.         }
  340.  
  341.     }
  342.  
  343.  
  344.  
  345.  
  346.  
  347.  
  348.     private class Thread_slanje extends Thread {
  349.  
  350.         private Context kontekst;
  351.         private SensorManager sManager = null;
  352.         private Sensor senzor;
  353.         private SensorEventListener senzor_listener;
  354.         private HandlerThread handler_thr;
  355.         private double x, y, z;
  356.  
  357.  
  358.         public Thread_slanje(Context context) {
  359.             kontekst = context;
  360.         }
  361.  
  362.  
  363.  
  364.             @Override
  365.             public void run() {
  366.  
  367.                 sManager = (SensorManager) kontekst.getSystemService(Context.SENSOR_SERVICE);
  368.                 senzor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  369.                 handler_thr = new HandlerThread("AccelerometerLogListener");
  370.                 handler_thr.start();
  371.                 Handler handler = new Handler(handler_thr.getLooper());
  372.  
  373.  
  374.  
  375.                 senzor_listener = new SensorEventListener() {
  376.                     @Override
  377.                     public void onSensorChanged(SensorEvent event) {
  378.                         WindowManager windowMgr = (WindowManager) kontekst.getSystemService(Context.WINDOW_SERVICE);
  379.                         int rotationIndex = windowMgr.getDefaultDisplay().getRotation();
  380.  
  381.                         if(btSocket2 != null) {
  382.                             if (rotationIndex == 1 || rotationIndex == 3) {
  383.                                 // detect 90 or 270 degree rotation
  384.                                 x = -event.values[1];
  385.                                 y = event.values[0];
  386.                                 z = event.values[2];
  387.  
  388.                             } else {
  389.                                 x = event.values[0];
  390.                                 y = event.values[1];
  391.                                 z = event.values[2];
  392.  
  393.                             }
  394.  
  395.                             sendEventValues();
  396.                         }
  397.                         else{
  398.                             kill_thr();     // THREAD ZAVRŠAVA AKO JE isConnected = false           ALI SE MOŽDA POZIVA U CONN THREADU DI JE IF THR IS ALIVE
  399.                         }
  400.                     }
  401.  
  402.                     @Override
  403.                     public void onAccuracyChanged(Sensor sensor, int accuracy) {
  404.  
  405.                     }
  406.  
  407.  
  408.                     private void sendMotor(String cmdSendLR) {
  409.                         if (btSocket2 != null) {
  410.                             try {
  411.                                 btSocket2.getOutputStream().write(cmdSendLR.getBytes());
  412.                             } catch (IOException e) {
  413.                                 e.printStackTrace();
  414.                             }
  415.                         }
  416.                     }
  417.  
  418.                     private void sendEventValues() {
  419.  
  420.  
  421.                         if (btSocket2 != null) {
  422.                             int xx = (int) Math.round(x);
  423.                             int yy = (int) Math.round(y);
  424.                             sendMotor("<" + xx + "," + yy + ">");
  425.                             Log.d("Slanje","podaci: "+xx+"\t"+yy);
  426.                             try {
  427.                                 Thread.sleep(50);
  428.                             } catch (InterruptedException ex) {
  429.                                 Thread.currentThread().interrupt();
  430.                             }
  431.                         }
  432.  
  433.                     }
  434.  
  435.                     private void onResume() {
  436.                        // super.onResume();
  437.                         sManager.registerListener(this, senzor, SensorManager.SENSOR_DELAY_NORMAL);
  438.                     }
  439.  
  440.                     private void onPause() {
  441.                       //  super.onPause();
  442.                         sManager.unregisterListener(this);
  443.                     }
  444.  
  445.                 };
  446.  
  447.                 sManager.registerListener(senzor_listener, senzor, SensorManager.SENSOR_DELAY_NORMAL, handler);
  448.             }
  449.  
  450.  
  451.     public void kill_thr(){
  452.  
  453.         if(sManager != null) {
  454.             sManager.unregisterListener(senzor_listener);
  455.         }
  456.  
  457.         if(handler_thr.isAlive())
  458.             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
  459.                 handler_thr.quitSafely();
  460.             }
  461.             else{
  462.                 handler_thr.quit();
  463.                 Log.d("HANDLER_THREAD","EXITED UNSAFELY");
  464.             }
  465.  
  466.     }
  467. }
  468. }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////KRAJ
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement