Home » Java » java – Send Android-Phone pitch and roll data to RPI with wifi direct-Exceptionshub

java – Send Android-Phone pitch and roll data to RPI with wifi direct-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

For my final year exam i need to send 2 float values (Pitch and Roll) from an Android phone to an RPI. This is what i got so far:

MainActivity:


import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import android.widget.TextView;
import android.widget.Toast;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

// References
// https://developer.android.com/training/connect-devices-wirelessly/wifi-direct#java
// https://developer.android.com/guide/topics/connectivity/wifip2p
// https://stackoverflow.com/questions/20339942/get-device-angle-by-using-getorientation-function
// https://developer.android.com/reference/android/hardware/SensorManager
// https://www.ssaurel.com/blog/get-android-device-rotation-angles-with-accelerometer-and-geomagnetic-sensors/

public class MainActivity extends AppCompatActivity
{
   // Generate objects & variables
   Button btnDiscover;
   Button btnSend;
   Button btnContinue;
   ListView lstView;
   EditText sendMsg;
   TextView connectionStatus;

   WifiP2pManager p2pManager;
   Channel p2pChannel;
   WifiP2pDevice[] devices;

   BroadcastReceiver p2pReceiver;
   IntentFilter p2pIntentFilter;

   List<WifiP2pDevice> peerList = new ArrayList<>();
   String[] deviceNames;
   int counter;

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       initialiseObjects();
       peerListener();
       connectionListener();

       btnContinue.setEnabled(false);
   }

   private void peerListener()
   {
       btnDiscover.setOnClickListener(new View.OnClickListener()
       {
           @Override
           public void onClick(View view)
           {
               p2pManager.discoverPeers(p2pChannel, new ActionListener()
               {
                   @Override
                   public void onSuccess()
                   {
                       connectionStatus.setText("Discovered Peers");
                   }

                   @Override
                   public void onFailure(int i)
                   {
                       connectionStatus.setText("Discovering failed");
                   }
               });
           }
       });
   }

   private void connectionListener()
   {
      lstView.setOnItemClickListener(new AdapterView.OnItemClickListener()
      {
          @Override
          public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
          {
              final WifiP2pDevice p2pDevice = devices[i];
              WifiP2pConfig config = new WifiP2pConfig();
              config.deviceAddress = p2pDevice.deviceAddress;
              config.wps.setup = WpsInfo.PBC;

              p2pManager.connect(p2pChannel, config, new ActionListener()
              {
                  @Override
                  public void onSuccess()
                  {
                      Toast.makeText(getApplicationContext(), "Connected to" + p2pDevice.deviceName, Toast.LENGTH_SHORT).show();
                      btnContinue.setEnabled(true);
                  }

                  @Override
                  public void onFailure(int i)
                  {
                      Toast.makeText(getApplicationContext(), "Not connected", Toast.LENGTH_SHORT).show();
                  }
              });
          }
      });
   }

   PeerListListener peerListListener =  new PeerListListener()
   {
       @Override
       public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList)
       {
           if(!wifiP2pDeviceList.getDeviceList().equals(peerList))
           {
               peerList.clear();
               peerList.addAll(wifiP2pDeviceList.getDeviceList());

               deviceNames = new String[wifiP2pDeviceList.getDeviceList().size()];
               devices = new WifiP2pDevice[wifiP2pDeviceList.getDeviceList().size()];

               counter = 0;

               for(WifiP2pDevice device : wifiP2pDeviceList.getDeviceList())
               {
                   deviceNames[counter] = device.deviceName;
                   devices[counter] = device;
                   counter++;
               }

               ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, deviceNames);
               lstView.setAdapter(adapter);

               if(peerList.size() == 0)
               {
                   Toast.makeText(getApplicationContext(), "No Devices Found", Toast.LENGTH_SHORT).show();
                   return;
               }
           }
       }
   };


   ConnectionInfoListener connectionInfoListener = new ConnectionInfoListener()
   {
       @Override
       public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo)
       {
           InetAddress groupOwnerAddress = wifiP2pInfo.groupOwnerAddress;

           if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner)
           {
               connectionStatus.setText("Host");
           }
           else if(wifiP2pInfo.groupFormed)
           {
               connectionStatus.setText("Client");
           }
       }
   };

   @Override
   protected void onResume()
   {
       super.onResume();
       registerReceiver(p2pReceiver, p2pIntentFilter);
   }

   @Override
   protected void onPause()
   {
       super.onPause();
       unregisterReceiver(p2pReceiver);
   }

   private void initialiseObjects()
   {
       btnDiscover = findViewById(R.id.btnPeers);
       btnSend = findViewById(R.id.btnTest);
       btnContinue = findViewById(R.id.btnContinue);
       lstView = findViewById(R.id.ltvPeers);
       sendMsg = findViewById(R.id.editText);
       connectionStatus = findViewById(R.id.txtConnectionStatus);

       p2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
       p2pChannel = p2pManager.initialize(this, getMainLooper(), null);
       p2pReceiver = new BroadcastReceiverP2P(p2pManager, p2pChannel, this);

       p2pIntentFilter = new IntentFilter();
       p2pIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
       p2pIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
       p2pIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
       p2pIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
   }

   public void sendDataActivity(View v)
   {
       Intent i = new Intent(this, SendData.class);
       startActivity(i);
   }
}

With that I am connecting to the RPI. Now i want to start another activity where I get the pitch and roll data and send it


import androidx.appcompat.app.AppCompatActivity;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

public class SendData extends AppCompatActivity implements SensorEventListener
{
    private SensorManager mSensorManager;
    Sensor accelerometer;
    Sensor magnetometer;

    float mGravity[] = new float[9];
    float mMagnetic[] = new float[9];
    float mAccels[] = new float[3];
    float mMags[] = new float[3];
    float[] mValues = new float[3];
    float[] outGravity = new float[9];
    float pitch;
    float roll;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_data);

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        magnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        mSensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event)
    {
        if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
        {
            mAccels = event.values.clone();
        }
        if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
        {
            mMags = event.values.clone();
        }

        if(mGravity != null && mMagnetic != null)
        {
            SensorManager.getRotationMatrix(mGravity, mMagnetic, mAccels, mMags);
            SensorManager.remapCoordinateSystem(mGravity, SensorManager.AXIS_X, SensorManager.AXIS_Z, outGravity);
            SensorManager.getOrientation(outGravity, mValues);
        }

        pitch = mValues[1] * 57.2957795f;
        roll = mValues[2] * 57.2957795f;
        mMags = null;
        mAccels = null;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i)
    {

    }
}

Now first, I don’t know how to send data yet, and second, I don’t know where I have to put that code. Can I put it in my second activity or do i have to create another one? I’m a freshman in java and app programming so I don’t understand complex terms.

How to&Answers: