Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.projekttest.gospodin.bluetooth_rc_auto.Akcelerometar;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothSocket;
- import android.content.Context;
- import android.hardware.Sensor;
- import android.hardware.SensorEvent;
- import android.hardware.SensorEventListener;
- import android.hardware.SensorManager;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.HandlerThread;
- import android.support.v7.app.AppCompatActivity;
- import android.util.Log;
- import android.view.View;
- import android.view.WindowManager;
- import android.widget.Button;
- import android.widget.TextView;
- import com.projekttest.gospodin.bluetooth_rc_auto.R;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.lang.reflect.Method;
- import java.util.UUID;
- public class Akcelerometar_Activity extends AppCompatActivity {
- private TextView textX, textY, textZ;
- private Button btnF, btnB, btnL, btnR, btnDis;
- private BluetoothAdapter btAdapter2 = null;
- private BluetoothDevice btDevice2 = null;
- private NativeBluetoothSocket btSocket2 = null;
- private boolean isConnected = false;
- private static final UUID DEFAULT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
- private String mac_adr = null;
- private boolean secure;
- ////////////////// NOVI SENSOREVENTLISTENER U THREADU
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_akcelerometar);
- textX = (TextView) findViewById(R.id.textX);
- textY = (TextView) findViewById(R.id.textY);
- textZ = (TextView) findViewById(R.id.textZ);
- btnF = (Button) findViewById(R.id.btnF);
- btnB = (Button) findViewById(R.id.btnB);
- btnL = (Button) findViewById(R.id.btnL);
- btnR = (Button) findViewById(R.id.btnR);
- btnDis= (Button) findViewById(R.id.btnDis);
- mac_adr = getIntent().getStringExtra("MACadr");
- Log.d("MACadresa",""+mac_adr);
- btAdapter2 = BluetoothAdapter.getDefaultAdapter();
- btDevice2 = btAdapter2.getRemoteDevice(mac_adr);
- Log.d("BLUETOOTHDEVICE","Uređaj: "+btDevice2+"\tAdapter: "+btAdapter2);
- ConnectThread thr = new ConnectThread(btDevice2, btAdapter2);
- thr.start();
- btnDis.setOnClickListener(new View.OnClickListener() {
- public void onClick(View v) {
- if(btSocket2 != null){
- try {
- btSocket2.close();
- Log.d("Disconnect","Disconnected");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- });
- }
- private class ConnectThread extends Thread {
- private final BluetoothDevice bTDevice;
- private final BluetoothSocket btSocket;
- private final BluetoothAdapter btAdapter;
- public ConnectThread(BluetoothDevice bTDevice1, BluetoothAdapter adapter) {
- BluetoothSocket tmp = null;
- bTDevice = bTDevice1;
- btAdapter = adapter;
- try {
- tmp = createBluetoothSocket(bTDevice);
- Log.e("KONEKCIJA", "Socket's create() SUCCESS");
- } catch (IOException e) {
- Log.e("KONEKCIJA", "Socket's create() method failed", e);
- }
- btSocket = tmp;
- }
- public void run() {
- btAdapter.cancelDiscovery();
- try {
- Thread.sleep(1000);
- connect(); ///////// funkcija koja pokrece sve ostale ispod
- if(btSocket != null){
- isConnected = true;
- try {
- Thread_slanje thr_slanje = new Thread_slanje(Akcelerometar_Activity.this.getApplicationContext());
- thr_slanje.start();
- Log.d("THREAD_SLANJE", "Start");
- } catch (Exception e) {
- Log.d("THREAD_SLANJE", "Error");
- }
- }
- Log.d("BTdevice: ", "Connected");
- } catch (IOException e) {
- e.printStackTrace();
- try {
- btSocket.close();
- Log.d("BTSOCKET: ", "CLOSED");
- } catch (IOException e1) {
- Log.d("BTdevice", "Could not close the client socket");
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- Log.d("THREAD", "INTERRUPTED");
- }
- }
- }
- private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
- if(Build.VERSION.SDK_INT >= 10){
- try {
- final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
- return (BluetoothSocket) m.invoke(device, DEFAULT_UUID);
- } catch (Exception e) {
- Log.e("CREATE_BT_SOCKET", "Could not create Insecure RFComm Connection",e);
- }
- }
- return device.createRfcommSocketToServiceRecord(DEFAULT_UUID);
- }
- public NativeBluetoothSocket connect() throws IOException {
- boolean success = false;
- while (selectSocket()) {
- btAdapter2.cancelDiscovery();
- try {
- btSocket2.connect();
- success = true;
- break;
- } catch (IOException e) {
- //fallback
- try {
- btSocket2 = new FallbackBluetoothSocket(btSocket2.getUnderlyingSocket());
- Thread.sleep(500);
- btSocket2.connect();
- success = true;
- break;
- } catch (FallbackException e1) {
- Log.w("BT", "Could not initialize FallbackBluetoothSocket classes.", e);
- } catch (InterruptedException e1) {
- Log.w("BT", e1.getMessage(), e1);
- } catch (IOException e1) {
- Log.w("BT", "Fallback failed. Cancelling.", e1);
- }
- }
- }
- if (!success) {
- throw new IOException("Could not connect to device: "+ btDevice2.getAddress());
- }
- return btSocket2;
- }
- private boolean selectSocket() throws IOException {
- BluetoothSocket tmp;
- Log.i("BT", "Attempting to connect to Protocol: "+ DEFAULT_UUID);
- if (secure) {
- tmp = btDevice2.createRfcommSocketToServiceRecord(DEFAULT_UUID);
- } else {
- tmp = btDevice2.createInsecureRfcommSocketToServiceRecord(DEFAULT_UUID);
- }
- btSocket2 = new NativeBluetoothSocket(tmp);
- return true;
- }
- public static interface BluetoothSocketWrapper {
- InputStream getInputStream() throws IOException;
- OutputStream getOutputStream() throws IOException;
- String getRemoteDeviceName();
- void connect() throws IOException;
- String getRemoteDeviceAddress();
- void close() throws IOException;
- BluetoothSocket getUnderlyingSocket();
- }
- public class NativeBluetoothSocket implements BluetoothSocketWrapper {
- private BluetoothSocket socket;
- public NativeBluetoothSocket(BluetoothSocket tmp) {
- this.socket = tmp;
- }
- @Override
- public InputStream getInputStream() throws IOException {
- return socket.getInputStream();
- }
- @Override
- public OutputStream getOutputStream() throws IOException {
- return socket.getOutputStream();
- }
- @Override
- public String getRemoteDeviceName() {
- return socket.getRemoteDevice().getName();
- }
- @Override
- public void connect() throws IOException {
- socket.connect();
- }
- @Override
- public String getRemoteDeviceAddress() {
- return socket.getRemoteDevice().getAddress();
- }
- @Override
- public void close() throws IOException {
- socket.close();
- }
- @Override
- public BluetoothSocket getUnderlyingSocket() {
- return socket;
- }
- }
- public class FallbackBluetoothSocket extends NativeBluetoothSocket {
- private BluetoothSocket fallbackSocket;
- public FallbackBluetoothSocket(BluetoothSocket tmp) throws FallbackException {
- super(tmp);
- try
- {
- Class<?> clazz = tmp.getRemoteDevice().getClass();
- Class<?>[] paramTypes = new Class<?>[] {Integer.TYPE};
- Method m = clazz.getMethod("createRfcommSocket", paramTypes);
- Object[] params = new Object[] {Integer.valueOf(1)};
- fallbackSocket = (BluetoothSocket) m.invoke(tmp.getRemoteDevice(), params);
- }
- catch (Exception e)
- {
- throw new FallbackException(e);
- }
- }
- @Override
- public InputStream getInputStream() throws IOException {
- return fallbackSocket.getInputStream();
- }
- @Override
- public OutputStream getOutputStream() throws IOException {
- return fallbackSocket.getOutputStream();
- }
- @Override
- public void connect() throws IOException {
- fallbackSocket.connect();
- }
- @Override
- public void close() throws IOException {
- fallbackSocket.close();
- }
- }
- public static class FallbackException extends Exception {
- private static final long serialVersionUID = 1L;
- public FallbackException(Exception e) {
- super(e);
- }
- }
- private class Thread_slanje extends Thread {
- private Context kontekst;
- private SensorManager sManager = null;
- private Sensor senzor;
- private SensorEventListener senzor_listener;
- private HandlerThread handler_thr;
- private double x, y, z;
- public Thread_slanje(Context context) {
- kontekst = context;
- }
- @Override
- public void run() {
- sManager = (SensorManager) kontekst.getSystemService(Context.SENSOR_SERVICE);
- senzor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
- handler_thr = new HandlerThread("AccelerometerLogListener");
- handler_thr.start();
- Handler handler = new Handler(handler_thr.getLooper());
- senzor_listener = new SensorEventListener() {
- @Override
- public void onSensorChanged(SensorEvent event) {
- WindowManager windowMgr = (WindowManager) kontekst.getSystemService(Context.WINDOW_SERVICE);
- int rotationIndex = windowMgr.getDefaultDisplay().getRotation();
- if(btSocket2 != null) {
- if (rotationIndex == 1 || rotationIndex == 3) {
- // detect 90 or 270 degree rotation
- x = -event.values[1];
- y = event.values[0];
- z = event.values[2];
- } else {
- x = event.values[0];
- y = event.values[1];
- z = event.values[2];
- }
- sendEventValues();
- }
- else{
- kill_thr(); // THREAD ZAVRŠAVA AKO JE isConnected = false ALI SE MOŽDA POZIVA U CONN THREADU DI JE IF THR IS ALIVE
- }
- }
- @Override
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
- private void sendMotor(String cmdSendLR) {
- if (btSocket2 != null) {
- try {
- btSocket2.getOutputStream().write(cmdSendLR.getBytes());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- private void sendEventValues() {
- if (btSocket2 != null) {
- int xx = (int) Math.round(x);
- int yy = (int) Math.round(y);
- sendMotor("<" + xx + "," + yy + ">");
- Log.d("Slanje","podaci: "+xx+"\t"+yy);
- try {
- Thread.sleep(50);
- } catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
- }
- }
- }
- private void onResume() {
- // super.onResume();
- sManager.registerListener(this, senzor, SensorManager.SENSOR_DELAY_NORMAL);
- }
- private void onPause() {
- // super.onPause();
- sManager.unregisterListener(this);
- }
- };
- sManager.registerListener(senzor_listener, senzor, SensorManager.SENSOR_DELAY_NORMAL, handler);
- }
- public void kill_thr(){
- if(sManager != null) {
- sManager.unregisterListener(senzor_listener);
- }
- if(handler_thr.isAlive())
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
- handler_thr.quitSafely();
- }
- else{
- handler_thr.quit();
- Log.d("HANDLER_THREAD","EXITED UNSAFELY");
- }
- }
- }
- }/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////KRAJ
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement