Advertisement
Guest User

Untitled

a guest
Dec 18th, 2015
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 76.71 KB | None | 0 0
  1. package com.example.platypuscontrolapp;
  2. //code load waypoitns from file
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.InputStreamReader;
  9. import java.io.OutputStreamWriter;
  10. import java.net.HttpURLConnection;
  11. import java.net.InetAddress;
  12. import java.net.InetSocketAddress;
  13. import java.net.SocketAddress;
  14. import java.net.URL;
  15. import java.text.DecimalFormat;
  16. import java.util.ArrayList;
  17. import java.util.Arrays;
  18. import java.util.List;
  19. import java.util.Scanner;
  20. import java.util.regex.Matcher;
  21. import java.util.regex.Pattern;
  22. import java.util.regex.PatternSyntaxException;
  23.  
  24. import javax.measure.unit.NonSI;
  25. import javax.measure.unit.SI;
  26.  
  27. import org.jscience.geography.coordinates.LatLong;
  28. import org.jscience.geography.coordinates.UTM;
  29. import org.jscience.geography.coordinates.crs.ReferenceEllipsoid;
  30.  
  31. import com.mapbox.mapboxsdk.api.ILatLng;
  32. import com.mapbox.mapboxsdk.constants.MapboxConstants;
  33. import com.mapbox.mapboxsdk.clustering.projection.Point;
  34. import com.mapbox.mapboxsdk.constants.MapboxConstants;
  35. import com.mapbox.mapboxsdk.geometry.BoundingBox;
  36. import com.mapbox.mapboxsdk.geometry.CoordinateRegion;
  37. import com.mapbox.mapboxsdk.geometry.CoordinateSpan;
  38. import com.mapbox.mapboxsdk.geometry.LatLng;
  39. import com.mapbox.mapboxsdk.offline.OfflineMapDatabase;
  40. import com.mapbox.mapboxsdk.offline.OfflineMapDownloader;
  41. import com.mapbox.mapboxsdk.offline.OfflineMapDownloaderListener;
  42. import com.mapbox.mapboxsdk.overlay.Icon;
  43. import com.mapbox.mapboxsdk.overlay.Marker;
  44. import com.mapbox.mapboxsdk.overlay.OfflineMapTileProvider;
  45. import com.mapbox.mapboxsdk.overlay.Overlay;
  46. import com.mapbox.mapboxsdk.overlay.TilesOverlay;
  47. import com.mapbox.mapboxsdk.overlay.UserLocationOverlay;
  48. import com.mapbox.mapboxsdk.tileprovider.tilesource.*;
  49. import com.mapbox.mapboxsdk.views.MapView;
  50. import com.mapbox.mapboxsdk.views.util.Projection;
  51. import com.mapbox.mapboxsdk.views.util.TilesLoadedListener;
  52.  
  53. import android.content.ComponentCallbacks;
  54. import android.graphics.Canvas;
  55. import android.graphics.drawable.BitmapDrawable;
  56. import android.graphics.drawable.Drawable;
  57. import android.net.ConnectivityManager;
  58. import android.nfc.Tag;
  59.  
  60. import android.view.MotionEvent;
  61. import android.view.View;
  62. import android.graphics.Matrix;
  63.  
  64.  
  65. import com.platypus.crw.CrwNetworkUtils;
  66. import com.platypus.crw.CrwNetworkUtils.*;
  67. import com.platypus.crw.SensorListener;
  68. import com.platypus.crw.VehicleServer;
  69. import com.platypus.crw.data.SensorData;
  70. import robotutils.Pose3D;
  71. import android.app.Activity;
  72. import android.content.Context;
  73.  
  74. import android.content.DialogInterface;
  75. import android.content.Intent;
  76. import android.graphics.Bitmap;
  77. import android.graphics.BitmapFactory;
  78. import android.graphics.Color;
  79. import android.hardware.Sensor;
  80. import android.hardware.SensorEvent;
  81. import android.hardware.SensorEventListener;
  82. import android.hardware.SensorManager;
  83. import android.os.AsyncTask;
  84. import android.os.Bundle;
  85. import android.os.Handler;
  86. import android.util.Log;
  87. import android.view.View;
  88. import android.widget.ArrayAdapter;
  89. import android.widget.Button;
  90. import android.widget.CheckBox;
  91. import android.widget.EditText;
  92. import android.widget.ImageView;
  93. import android.widget.LinearLayout;
  94. import android.widget.ListView;
  95. import android.widget.RadioButton;
  96. import android.widget.RadioGroup;
  97. import android.widget.RelativeLayout;
  98. import android.widget.SeekBar;
  99. import android.widget.TextView;
  100. import android.widget.Toast;
  101. import android.widget.ToggleButton;
  102. import android.widget.ProgressBar;
  103.  
  104. import java.util.Map;
  105. import com.platypus.crw.udp.UdpVehicleServer;
  106.  
  107. import com.platypus.crw.FunctionObserver;
  108. import com.platypus.crw.ImageListener;
  109. import com.platypus.crw.PoseListener;
  110. import com.platypus.crw.SensorListener;
  111. import com.platypus.crw.VehicleServer.WaypointState;
  112. import com.platypus.crw.VelocityListener;
  113. import com.platypus.crw.WaypointListener;
  114. import com.platypus.crw.data.Twist;
  115. import com.platypus.crw.data.Utm;
  116. import com.platypus.crw.data.UtmPose;
  117.  
  118. import android.app.Dialog;
  119. import android.app.AlertDialog;
  120.  
  121. import android.view.View.OnClickListener;
  122. import com.example.platypuscontrolapp.Joystick.*;
  123.  
  124.  
  125. public class TeleOpPanel extends Activity implements SensorEventListener {
  126.     final Context context = this;
  127.     SeekBar thrust = null;
  128.     SeekBar rudder = null;
  129.     TextView ipAddressBox = null;
  130.     TextView thrustProgress = null;
  131.     TextView rudderProgress = null;
  132.     RelativeLayout linlay = null;
  133.     CheckBox autonomous = null;
  134.     Button mapButton = null;
  135.     static TextView testIP = null;
  136.     AsyncTask networkThread;
  137.     TextView test = null;
  138.     ToggleButton tiltButton = null;
  139.     ToggleButton waypointButton = null;
  140.  
  141.  
  142.     Button deleteWaypoint = null;
  143.     Button connectButton = null;
  144.     Button saveMap = null;
  145.     Button loadMap = null;
  146.     Button removeMap = null;
  147.     Button refreshMap = null;
  148.     //TextView log = null;
  149.     Handler network = new Handler();
  150.     ImageView cameraStream = null;
  151.     Button loadWPFile = null;
  152.  
  153.     TextView sensorData1 = null;
  154.     TextView sensorData2 = null;
  155.     TextView sensorData3 = null;
  156.  
  157.     TextView sensorType1 = null;
  158.     TextView sensorType2 = null;
  159.     TextView sensorType3 = null;
  160.     TextView battery = null;
  161.  
  162.     ToggleButton sensorvalueButton = null;
  163.     JoystickView joystick;
  164.     ProgressBar progressBar;
  165.  
  166.  
  167.  
  168.     boolean checktest;
  169.     int a = 0;
  170.  
  171.     double xValue;
  172.     double yValue;
  173.     double zValue;
  174.     LatLong latlongloc;
  175.     LatLng boatLocation;
  176.  
  177.  
  178.     MapView mv;
  179.     String zone;
  180.     String rotation;
  181.  
  182.     TextView loca = null;
  183.     //Marker boat;
  184.     Marker boat2;
  185.     Marker compass;
  186.  
  187.     LatLng pHollowStartingPoint = new LatLng((float) 40.436871,
  188.             (float) -79.948825);
  189.     LatLng UCMerced = new LatLng((float)37.400732,(float) -120.487372);
  190.     LatLng Mapcenter ;
  191.     long lastTime = -1;
  192.     double lat = 10;
  193.     double lon = 10;
  194.     String waypointStatus = "";
  195.     Handler handlerRudder = new Handler();
  196.     int thrustCurrent;
  197.     int rudderCurrent;
  198.     double heading = Math.PI / 2.;
  199.     double rudderTemp = 0;
  200.     double thrustTemp = 0;
  201.     double old_rudder=0;
  202.     double old_thrust=0;
  203.     double temp;
  204.     double rot;
  205.     String boatwaypoint;
  206.     double tempThrustValue = 0; //used for abs value of thrust
  207.     Twist twist = new Twist();
  208.  
  209.     float tempX = 0;
  210.     float tempY = 0;
  211.  
  212.     Bitmap currentImage = null;
  213.     boolean isAutonomous;
  214.     boolean isCurrentWaypointDone = true;
  215.  
  216.     SensorManager senSensorManager;
  217.     Sensor senAccelerometer;
  218.     public boolean stopWaypoints = true;
  219.     private long lastUpdate = 0;
  220.     private float last_x, last_y, last_z;
  221.     private static final int SHAKE_THRESHOLD = 600;
  222.  
  223.     public static final double THRUST_MIN = -1.0;
  224.     public static final double THRUST_MAX = 1.0;
  225.     public static final double RUDDER_MIN = 1.0;
  226.     public static final double RUDDER_MAX = -1.0;
  227.  
  228.     public EditText ipAddress = null;
  229.     public EditText color = null;
  230.     public RadioButton actualBoat = null;
  231.     public RadioButton simulation = null;
  232.     public Button startWaypoints = null;
  233.  
  234.     public RadioButton direct = null;
  235.     public RadioButton reg = null;
  236.  
  237.     public Button submitButton = null;
  238.     public static RadioGroup simvsact = null;
  239.     public static String textIpAddress;
  240.     public static boolean simul = false;
  241.     public static boolean actual;
  242.     public static Boat currentBoat;
  243.     public static InetSocketAddress address;
  244.     public CheckBox autoBox;
  245.     private final Object _waypointLock = new Object(); //deadlock?!??
  246.     boolean failedwp = true;
  247.  
  248.     public int wpcount = 0;
  249.     public String wpstirng = "";
  250.     public int channel =0;
  251.     public double[] data;
  252.     SensorData Data;
  253.     public String sensorV = "Loading...";
  254.     public static int counter = 0;
  255.     public TextView sensorValueBox;
  256.     boolean dialogClosed = false;
  257.     boolean sensorReady =false;
  258.     public static TextView log;
  259.     public boolean Auto = false;
  260.     private String MapID = "shantanuv.nkob79p0";
  261.     Dialog connectDialog;
  262.     private PoseListener pl;
  263.     private SensorListener sl;
  264.  
  265.  
  266.  
  267.     List<ILatLng> waypointList = new ArrayList<ILatLng>();
  268.     List<Marker> markerList = new ArrayList(); //List of all the
  269.     //markers on the map
  270.     //corresponding to the
  271.     //given way
  272.  
  273.     OfflineMapDownloader offlineMapDownloader;
  274.     TilesOverlay offlineMapOverlay;
  275.     LatLng OfflineCenter = null ;
  276.  
  277.     private static final String logTag = TeleOpPanel.class.getName();
  278.  
  279.     protected void onCreate(Bundle savedInstanceState)   {
  280.         super.onCreate(savedInstanceState);
  281.  
  282.        //this.setContentView(R.layout.tabletlayout_lg8);  // layout for LG GpadF 8
  283.        this.setContentView(R.layout.tabletlayout); // layout for Nexus 10
  284.  
  285.         ipAddressBox = (TextView) this.findViewById(R.id.printIpAddress);
  286.         //thrust = (SeekBar) this.findViewById(R.id.thrustBar);
  287.         //rudder = (SeekBar) this.findViewById(R.id.rudderBar);
  288.         linlay = (RelativeLayout) this.findViewById(R.id.linlay);
  289.         thrustProgress = (TextView) this.findViewById(R.id.getThrustProgress);
  290.         rudderProgress = (TextView) this.findViewById(R.id.getRudderProgress);
  291.         // test = (TextView) this.findViewById(R.id.test12);
  292.         //tiltButton = (ToggleButton) this.findViewById(R.id.tiltButton);
  293.         waypointButton = (ToggleButton) this.findViewById(R.id.waypointButton);
  294.         deleteWaypoint = (Button) this.findViewById(R.id.waypointDeleteButton);
  295.         connectButton = (Button) this.findViewById(R.id.connectButton);
  296.         log = (TextView) this.findViewById(R.id.log);
  297.        // loadWPFile = (Button)this.findViewById(R.id.loadFileButton);
  298.         autoBox = (CheckBox) this.findViewById(R.id.autonomousBox);
  299.         startWaypoints = (Button) this.findViewById(R.id.waypointStartButton);
  300.         sensorData1 = (TextView) this.findViewById(R.id.SValue1);
  301.         sensorData2 = (TextView) this.findViewById(R.id.SValue2);
  302.         sensorData3 = (TextView) this.findViewById(R.id.SValue3);
  303.         sensorType1 = (TextView) this.findViewById(R.id.sensortype1);
  304.         sensorType2 = (TextView) this.findViewById(R.id.sensortype2);
  305.         sensorType3 = (TextView) this.findViewById(R.id.sensortype3);
  306.         sensorvalueButton = (ToggleButton) this.findViewById(R.id.SensorStart);
  307.         sensorvalueButton.setClickable(sensorReady);
  308.         sensorvalueButton.setTextColor(Color.GRAY);
  309.         battery = (TextView)this.findViewById(R.id.batteryVoltage);
  310.  
  311.         saveMap = (Button) this.findViewById(R.id.saveMap);
  312.         loadMap = (Button) this.findViewById(R.id.loadMap);
  313.         removeMap = (Button) this.findViewById(R.id.removeMap);
  314.         refreshMap = (Button) this.findViewById(R.id.refreshMap);
  315.         progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
  316.         progressBar.setVisibility(View.GONE);
  317.  
  318.         //sensorvalueButton.setTextColor(Color.BLACK);
  319.         //sensorvalueButton.setText("Show SensorData");
  320.       //  sensorValueBox = (TextView) this.findViewById(R.id.SensorValue);
  321.         //thrust.setProgress(0); //initially set thrust to 0
  322.         //rudder.setProgress(50); //initially set rudder to center (50)
  323.  
  324.  
  325. //**********************************************************************
  326. //  faked sensor data
  327. //***********************************************************************
  328. //        sensorData1.setText("6.56");
  329. //        sensorType1.setText("ATLAS_PH \n pH");
  330. //        sensorData2.setText("9.56");
  331. //        sensorType2.setText("ATLAS_DO \n mg/L");
  332. //        sensorData3.setText("305\n19.0");
  333. //        sensorType3.setText("ES2 \nEC(µS/cm)\nTE(°C)");
  334. //        battery.setText("14.566");
  335.      // *****************//
  336.      //      Joystick   //
  337.      // ****************//
  338.         joystick = (JoystickView) findViewById(R.id.joystickView);
  339.         joystick.setYAxisInverted(false);
  340.  
  341. //*****************************************************************************
  342. //  Initialize Poselistener
  343. //*****************************************************************************
  344.         pl = new PoseListener() { //gets the location of the boat
  345.             public void receivedPose(UtmPose upwcs) {
  346.  
  347.                 UtmPose _pose = upwcs.clone();
  348.                 {
  349.                     xValue = _pose.pose.getX();
  350.                     yValue = _pose.pose.getY();
  351.                     zValue = _pose.pose.getZ();
  352.                     rotation = String.valueOf(Math.PI / 2
  353.                             - _pose.pose.getRotation().toYaw());
  354.                     rot =  Math.PI/2 - _pose.pose.getRotation().toYaw();
  355.  
  356.                     zone = String.valueOf(_pose.origin.zone);
  357.  
  358.                     latlongloc = UTM.utmToLatLong(UTM.valueOf(
  359.                                     _pose.origin.zone, 'T', _pose.pose.getX(),
  360.                                     _pose.pose.getY(), SI.METER),
  361.                             ReferenceEllipsoid.WGS84);
  362.  
  363.                     //Log.i(logTag, "rot:" + rot);
  364.                 }
  365.             }
  366.         };
  367.  
  368. //*******************************************************************************
  369. //  Initialize Sensorlistener
  370. //*******************************************************************************
  371.          sl = new SensorListener() {
  372.             @Override
  373.             public void receivedSensor(SensorData sensorData) {
  374.                 Data = sensorData;
  375.  
  376.                 sensorV = Arrays.toString(Data.data);
  377.                 sensorV = sensorV.substring(1, sensorV.length()-1);
  378.                 sensorReady = true;
  379.                 //Log.i("Platypus","Get sensor Data");
  380.             }
  381.         };
  382.  
  383. //****************************************************************************
  384. //  Initialize the Boat
  385. // ****************************************************************************
  386.         currentBoat = new Boat(pl, sl);
  387.        // currentBoat = new Boat();
  388.         //currentBoat.returnServer().addPoseListener(pl,null);
  389.  
  390. //        for (int channel = 0; channel < 5; channel++) {
  391. //            currentBoat.returnServer().addSensorListener(channel, sl, null);
  392. //        }
  393.  
  394.         senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
  395.         senAccelerometer = senSensorManager
  396.                 .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  397.         senSensorManager.registerListener(this, senAccelerometer,
  398.                 SensorManager.SENSOR_DELAY_NORMAL);
  399. //
  400. //        //cameraStream.setImageResource(R.drawable.streamnotfound);
  401.         //File file = new File("/Android/data/com.example.platypuscontrolapp/cache/mapbox_tiles_cache");
  402.         //final MBTilesLayer mbTilesLayer = new MBTilesLayer(file);
  403.         mv = (MapView) findViewById(R.id.mapview);
  404.         offlineMapDownloader = OfflineMapDownloader.getOfflineMapDownloader(this);
  405.         mv.setDiskCacheEnabled(false);
  406.         mv.setMapRotationEnabled(true);
  407.         //mv.setMapOrientation(-10f);
  408.         mv.setUserLocationEnabled(true);
  409.         compass = new Marker("Compass","",pHollowStartingPoint);
  410.         mv.addMarker(compass);
  411.  
  412.  
  413.         // If has Internet connection, using online map, else using offline map
  414.  
  415.             Thread thread = new Thread() {
  416.                 public void run() {
  417.                     if (isInternetAvailable()) {
  418.                         try {
  419.  
  420.                             mv.setAccessToken("pk.eyJ1Ijoic2hhbnRhbnV2IiwiYSI6ImNpZmZ0Zzd5Mjh4NW9zeG03NGMzNDI4ZGUifQ.QJgnm41kA9Wo3CJU-xZLTA");
  421.                             //mv.setTileSource(new MapboxTileLayer("mapbox.streets"));
  422.                             mv.setTileSource(new MapboxTileLayer(MapID));
  423.                             // mv.setTileSource(mbTilesLayer);
  424.  
  425.                             mv.setCenter(new ILatLng() {
  426.                                 @Override
  427.                                 public double getLatitude() {
  428.                                     return pHollowStartingPoint.getLatitude();
  429.                                 }
  430.  
  431.                                 @Override
  432.                                 public double getLongitude() {
  433.  
  434.                                     return pHollowStartingPoint.getLongitude();
  435.                                 }
  436.  
  437.                                 @Override
  438.                                 public double getAltitude() {
  439.                                     return 0;
  440.                                 }
  441.                             });
  442.  
  443.                             mv.setZoom(16);
  444.  
  445.  
  446. //                    mv.setOnTouchListener(new View.OnTouchListener() {
  447. //                        @Override
  448. //                        public boolean onTouch(View v, MotionEvent event) {
  449. //                            if (waypointButton.isChecked()) {
  450. //                                try {
  451. //                                    Thread.sleep(1000);
  452. //                                } catch (Exception e) {
  453. //
  454. //                                }
  455. //                                Projection proj = ((MapView) v).getProjection();
  456. //                                ILatLng touchedloc = proj.fromPixels(event.getX(), event.getY());
  457. //                                System.out.println("Location: " + touchedloc.toString());
  458. //                                LatLng templocc = new LatLng(touchedloc.getLatitude(), touchedloc.getLongitude());
  459. //                                Log.i(logTag, "Waypoint "+ templocc );
  460. //                                mv.addMarker(new Marker("First", " ", templocc));
  461. //                            }
  462. //                            return false;
  463. //                        }
  464. //                    });
  465.  
  466.  
  467.                         }catch(Exception e){
  468.                             System.err.println(e);
  469.                         }
  470.                     }
  471.                     else{
  472.                         if(offlineMapDownloader.getMutableOfflineMapDatabases() != null & offlineMapDownloader.getMutableOfflineMapDatabases().size()>0){
  473.                             //mv.setCenter(pHollowStartingPoint);
  474.                             //Thread threadoffline = new Thread(){
  475.                             //   public void run(){
  476.                             loadOfflineMap();
  477.                             //    }
  478.                             //  };
  479.                             //   threadoffline.start();
  480.                         }
  481.                         else{
  482.                             runOnUiThread(new Runnable() {
  483.                                 @Override
  484.                                 public void run() {
  485.                                     Toast.makeText(getApplicationContext(), "No OfflineMap available, Connect to Internet", Toast.LENGTH_LONG).show();
  486.                                 }
  487.                             });
  488.  
  489.                         }
  490.                     }
  491.                 }
  492.             };
  493.             thread.start();
  494.  
  495.  
  496.  
  497.  
  498.         connectButton.setOnClickListener(new OnClickListener() {
  499.             @Override
  500.             public void onClick(View view) {
  501.                 connectBox();
  502.             }
  503.         });
  504.  
  505.  
  506.  
  507.         connectBox();
  508.  
  509. //        loadWPFile.setOnClickListener(
  510. //                new OnClickListener() {
  511. //                    @Override
  512. //                    public void onClick(View view) {
  513. //                        try {
  514. //
  515. //                            if(setWaypointsFromFile()==false) {
  516. //                                failedwp = true;
  517. ////
  518. //                            }
  519. //                            else
  520. //                            {
  521. //                                failedwp = false;
  522. //                            }
  523. //                        }
  524. //                        catch(Exception e)
  525. //                        {
  526. //
  527. //                        }
  528. //                    }
  529. //                });
  530.  
  531. //        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
  532. //        alertDialog.setTitle("Add Waypoints from File");
  533. //        if (failedwp == true)
  534. //        {
  535. //            alertDialog.setMessage("Waypoint File was in the incorrect formatting. \n No Current Waypoints");
  536. //            waypointList.clear();
  537. //            for (Marker i : markerList) {
  538. //                i.remove();
  539. //            }
  540. //        }
  541. //        else {
  542. //            alertDialog.setMessage("Waypoints Added and Started");
  543. //        }
  544.  
  545. //        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
  546. //            public void onClick(DialogInterface dialog, int which) {
  547. //                alertDialog.dismiss();
  548. //            }
  549. //        });
  550.         //alertDialog.show();
  551.         //actual = true;
  552.  
  553.         /*
  554.          * This gets called when a boat is connected
  555.          * Note it has to draw the boat somewhere initially until it gets a gps loc so it draws it
  556.          * on PantherHollow lake until it gets a new gps loc and will then update to the current
  557.          * position
  558.          */
  559.  
  560.         startWaypoints.setOnClickListener(new OnClickListener() {
  561.             @Override
  562.             public void onClick(View view) {
  563.                 Thread thread = new Thread(){
  564.                     public void run(){
  565.                         if (currentBoat.isConnected() == true)
  566.                         {
  567.                             System.out.println("called");
  568.                             // System.out.println("waypointList > 0");
  569.                             checktest = true;
  570.                             UtmPose tempUtm = convertLatLngUtm(waypointList.get(waypointList.size() - 1));
  571.  
  572.                             waypointStatus = tempUtm.toString();
  573.  
  574.                             //System.out.println("wps" + waypointStatus);
  575.                             currentBoat.addWaypoint(tempUtm.pose, tempUtm.origin);
  576.                             UtmPose[] wpPose = new UtmPose[waypointList.size()];
  577.                             synchronized (_waypointLock) {
  578.                                 //wpPose[0] = new UtmPose(tempUtm.pose, tempUtm.origin);
  579.                                 for (int i = 0; i < waypointList.size(); i++)
  580.                                 {
  581.                                     wpPose[i] = convertLatLngUtm(waypointList.get(i));
  582.                                 }
  583.                             }
  584.  
  585.                             checkAndSleepForCmd();
  586.                             currentBoat.returnServer().startWaypoints(wpPose, "POINT_AND_SHOOT", new FunctionObserver<Void>() {
  587.                                 @Override
  588.                                 public void completed(Void aVoid) {
  589.                                     System.out.println("completed");
  590.                                 }
  591.  
  592.                                 @Override
  593.                                 public void failed(FunctionError functionError) {
  594.                                     isCurrentWaypointDone = false;
  595.                                     System.out.println("asdf");
  596.                                     // = waypointStatus + "\n" + functionError.toString();
  597.                                     // System.out.println(waypointStatus);
  598.                                 }
  599.                             });
  600.                             currentBoat.returnServer().getWaypoints(new FunctionObserver<UtmPose[]>() {
  601.                                 @Override
  602.                                 public void completed(UtmPose[] wps) {
  603.                                     for (UtmPose i : wps)
  604.                                     {
  605.                                         System.out.println("wp");
  606.                                         System.out.println(i.toString());
  607.                                     }
  608.                                 }
  609.                                 @Override
  610.                                 public void failed(FunctionError functionError) {
  611.                                     System.out.println("shit");
  612.                                 }
  613.                             });
  614.                         }
  615.  
  616.                     }
  617.                 };
  618.                 thread.start();
  619.             }
  620.         });
  621.  
  622.         waypointButton.setOnClickListener(new OnClickListener() {
  623.             @Override
  624.             public void onClick(View view) {
  625.                 Thread thread = new Thread() {
  626.                     public void run() {
  627.                         if (waypointButton.isChecked()) {
  628.                             Auto = true;
  629.                         } else {
  630.                             Auto = false;
  631.                         }
  632.                         if (Auto) {
  633.                             currentBoat.returnServer().setAutonomous(true, null);
  634.                         } else {
  635.                             currentBoat.returnServer().setAutonomous(false, null);
  636.                         }
  637.  
  638.                         currentBoat.returnServer().isAutonomous(new FunctionObserver<Boolean>() {
  639.                             @Override
  640.                             public void completed(Boolean aBoolean) {
  641.                                 isAutonomous = aBoolean;
  642.                                 Log.i(logTag, "isAutonomous: " + isAutonomous);
  643.                             }
  644.  
  645.                             @Override
  646.                             public void failed(FunctionError functionError) {
  647.  
  648.                             }
  649.                         });
  650.                     }
  651.                 };
  652.                 thread.start();
  653.             }
  654.         });
  655.         // download offline map
  656.         saveMap.setOnClickListener(new OnClickListener() {
  657.             @Override
  658.             public void onClick(View v) {
  659.                 if(offlineMapDownloader.isMapIdAlreadyAnOfflineMapDatabase(MapID)){
  660.                     Toast.makeText(getApplicationContext(), "MapID has already been downloaded.\n" +
  661.                             "Please remove it before trying to download again", Toast.LENGTH_SHORT).show();
  662.                 }
  663.                 Mapcenter = mv.getCenter();
  664.                 writeToFile(Mapcenter.toString());
  665.                 Thread thread = new Thread(){
  666.                     public void run(){
  667.                         saveOfflineMap(Mapcenter);
  668.                     }
  669.                 };
  670.                 thread.start();
  671.             }
  672.         });
  673.         // display offline map
  674.         loadMap.setOnClickListener(new OnClickListener() {
  675.             @Override
  676.             public void onClick(View v) {
  677.                 //loadOfflineMap();
  678.  
  679.                 Thread thread = new Thread(){
  680.                     public void run(){
  681.                         loadOfflineMap();
  682.                     }
  683.                 };
  684.                 thread.start();
  685.             }
  686.         });
  687.         // switch to online map
  688.         refreshMap.setOnClickListener(new OnClickListener() {
  689.             @Override
  690.             public void onClick(View v) {
  691.  
  692.                         if(isInternetAvailable()){
  693.                             mv.setAccessToken("pk.eyJ1Ijoic2hhbnRhbnV2IiwiYSI6ImNpZmZ0Zzd5Mjh4NW9zeG03NGMzNDI4ZGUifQ.QJgnm41kA9Wo3CJU-xZLTA");
  694.                             //mv.setTileSource(new MapboxTileLayer("mapbox.streets"));
  695.                             mv.setTileSource(new MapboxTileLayer(MapID));
  696.                         }
  697.                         else{
  698.                             Toast.makeText(getApplicationContext(),"Need Internet Connection", Toast.LENGTH_LONG).show();
  699.                         }
  700.  
  701.  
  702.             }
  703.         });
  704.         // remove offline map database
  705.         removeMap.setOnClickListener(new OnClickListener() {
  706.             @Override
  707.             public void onClick(View v) {
  708.                 offlineMapDownloader.removeOfflineMapDatabaseWithID(MapID);
  709.                 Toast.makeText(getApplicationContext(), "Removed OfflineMap", Toast.LENGTH_SHORT).show();
  710.                 progressBar.setProgress(0);
  711.                 String dir = getFilesDir().getAbsolutePath();
  712.                 File file = new File(dir, "Mapcenter.txt");
  713.                 file.delete();
  714.  
  715.  
  716.             }
  717.         });
  718.  
  719.  
  720.  
  721.  
  722.     }
  723.  
  724.     private void saveOfflineMap (LatLng Mapcenter){
  725.         offlineMapDownloader = OfflineMapDownloader.getOfflineMapDownloader(this);
  726.        // mv.setCenter(pHollowStartingPoint);
  727.        // mv.setZoom(17);
  728.  
  729.         //BoundingBox boundingBox = new BoundingBox(new LatLng(40.435203, -79.951636), new LatLng(40.439345, -79.944796));
  730.  
  731.         BoundingBox boundingBox = new BoundingBox(new LatLng(Mapcenter.getLatitude() -0.003,Mapcenter.getLongitude()-0.003), new LatLng(Mapcenter.getLatitude() +0.003,Mapcenter.getLongitude()+0.003));
  732.         CoordinateSpan span = new CoordinateSpan(boundingBox.getLatitudeSpan(), boundingBox.getLongitudeSpan());
  733.         CoordinateRegion coordinateRegion = new CoordinateRegion(Mapcenter, span);
  734.         offlineMapDownloader.beginDownloadingMapID(MapID, coordinateRegion, 17, 19);
  735.  
  736.         OfflineMapDownloaderListener listener = new OfflineMapDownloaderListener() {
  737.             @Override
  738.             public void stateChanged(OfflineMapDownloader.MBXOfflineMapDownloaderState newState) {
  739.                 Log.i(logTag, String.format(MapboxConstants.MAPBOX_LOCALE, "stateChanged to %s", newState));
  740.             }
  741.  
  742.             @Override
  743.             public void initialCountOfFiles(Integer numberOfFiles) {
  744.                 Log.i(logTag, String.format(MapboxConstants.MAPBOX_LOCALE, "File number = %d", numberOfFiles));
  745.             }
  746.  
  747.             @Override
  748.             public void progressUpdate(final Integer numberOfFilesWritten, final Integer numberOfFilesExcepted) {
  749.                 runOnUiThread(new Runnable() {
  750.                     @Override
  751.                     public void run() {
  752.                         if(progressBar.getVisibility() == View.GONE){
  753.                             progressBar.setVisibility(View.VISIBLE);
  754.                         }
  755.                         progressBar.setMax(numberOfFilesExcepted);
  756.                         progressBar.setProgress(numberOfFilesWritten);
  757.  
  758.                         if(numberOfFilesExcepted == numberOfFilesWritten){
  759.                             progressBar.setVisibility(View.GONE);
  760.                         }
  761.                     }
  762.                 });
  763.  
  764.             }
  765.  
  766.             @Override
  767.             public void networkConnectivityError(Throwable error) {
  768.  
  769.             }
  770.  
  771.             @Override
  772.             public void sqlLiteError(Throwable error) {
  773.  
  774.             }
  775.  
  776.             @Override
  777.             public void httpStatusError(Throwable error) {
  778.  
  779.             }
  780.  
  781.             @Override
  782.             public void completionOfOfflineDatabaseMap(OfflineMapDatabase offlineMapDatabase) {
  783.                 runOnUiThread(new Runnable() {
  784.                     @Override
  785.                     public void run() {
  786.                         Toast.makeText(getApplicationContext(), "Finish Saving Map", Toast.LENGTH_LONG).show();
  787.                         progressBar.setVisibility(View.GONE);
  788.                     }
  789.                 });
  790.  
  791.  
  792.             }
  793.         };
  794.         offlineMapDownloader.addOfflineMapDownloaderListener(listener);
  795.     }
  796.  
  797.     private void loadOfflineMap(){
  798.         ArrayList<OfflineMapDatabase> offlineMapDatabases = offlineMapDownloader.getMutableOfflineMapDatabases();
  799.         if(offlineMapDatabases != null & offlineMapDatabases.size()>0) {
  800.            // OfflineMapDatabase db = offlineMapDatabases.get(0);
  801.  
  802.            // OfflineMapTileProvider tp = new OfflineMapTileProvider(getApplicationContext(), db);
  803.            // offlineMapOverlay = new TilesOverlay(tp);
  804.  
  805.             //mv.addOverlay(offlineMapOverlay);
  806.  
  807.  
  808.             // mv.setZ(1.0f);
  809.  
  810.             // File file = new File("/data/data/com.example.platypuscontrolapp/databases/shantanuv.nkob79p0");
  811.  
  812.            // mv.setCenter(pHollowStartingPoint);
  813.             //mv.setZoom(17);
  814.             runOnUiThread(new Runnable() {
  815.                 @Override
  816.                 public void run() {
  817.                     Marker marker = new Marker("Test", "", pHollowStartingPoint);
  818.                     String mapcenter = readFromFile();
  819.                     String[] mc  = mapcenter.split(",", 3);
  820.                     double lat = Double.parseDouble(mc[0]);
  821.                     double lon = Double.parseDouble(mc[1]);
  822.                     mv.setCenter(new LatLng(lat, lon));
  823.                     mv.setZoom(17);
  824.                     mv.setTileSource(new MBTilesLayer(getApplicationContext(), "shantanuv.nkob79p0.mblite"));
  825.                     //mv.addOverlay(offlineMapOverlay);
  826.                    // mv.addMarker(marker);
  827.                     //mv.setTranslationZ(0);
  828.                     Toast.makeText(getApplicationContext(), "Loading OfflineMap", Toast.LENGTH_SHORT).show();
  829.                 }
  830.             });
  831.         }
  832.         else{
  833.             runOnUiThread(new Runnable() {
  834.                 @Override
  835.                 public void run() {
  836.                     Toast.makeText(getApplicationContext(), "OfflineMap is Unavailable", Toast.LENGTH_LONG).show();
  837.                 }
  838.             });
  839.  
  840.         }
  841.     }
  842.  
  843.     private void writeToFile(String data) {
  844.         try {
  845.             OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("Mapcenter.txt", Context.MODE_PRIVATE));
  846.             outputStreamWriter.write(data);
  847.             outputStreamWriter.close();
  848.         }
  849.         catch (IOException e) {
  850.             Log.e("Exception", "File write failed: " + e.toString());
  851.         }
  852.     }
  853.  
  854.  
  855.     private String readFromFile() {
  856.  
  857.         String ret = "";
  858.  
  859.         try {
  860.             InputStream inputStream = openFileInput("Mapcenter.txt");
  861.  
  862.             if ( inputStream != null ) {
  863.                 InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
  864.                 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  865.                 String receiveString = "";
  866.                 StringBuilder stringBuilder = new StringBuilder();
  867.  
  868.                 while ( (receiveString = bufferedReader.readLine()) != null ) {
  869.                     stringBuilder.append(receiveString);
  870.                 }
  871.  
  872.                 inputStream.close();
  873.                 bufferedReader.close();
  874.                 ret = stringBuilder.toString();
  875.             }
  876.         }
  877.         catch (FileNotFoundException e) {
  878.             Log.e("login activity", "File not found: " + e.toString());
  879.         } catch (IOException e) {
  880.             Log.e("login activity", "Can not read file: " + e.toString());
  881.         }
  882.  
  883.         return ret;
  884.     }
  885.     // This method checks the wifi connection but not Internet access
  886.     public static boolean isNetworkAvailable(final Context context) {
  887.         final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
  888.         return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
  889.     }
  890.     // This method need to run in another thread except UI thread(main thread)
  891.     public static boolean hasActiveInternetConnection(Context context) {
  892.         if (isNetworkAvailable(context)) {
  893.             try {
  894.  
  895.                 HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
  896.                 urlc.setRequestProperty("User-Agent", "Test");
  897.                 urlc.setRequestProperty("Connection", "close");
  898.                 urlc.setConnectTimeout(1500);
  899.                 urlc.connect();
  900.                 return (urlc.getResponseCode() == 200);
  901.             } catch (IOException e) {
  902.                 Log.e(logTag, "Error checking internet connection", e);
  903.             }
  904.         } else {
  905.             Log.d(logTag, "No network available!");
  906.         }
  907.         return false;
  908.     }
  909.     // Really Check Internet access
  910.     public Boolean isInternetAvailable() {
  911.         try {
  912.             Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1    www.google.com");
  913.             int returnVal = p1.waitFor();
  914.             boolean reachable = (returnVal==0);
  915.             if(reachable){
  916.                 Log.i(logTag, "Internet access");
  917.                 return reachable;
  918.             }
  919.             else{
  920.                 Log.i(logTag, "No Internet access");
  921.             }
  922.  
  923.         } catch (Exception e) {
  924.  
  925.             e.printStackTrace();
  926.         }
  927.         return false;
  928.     }
  929.     // *******************************
  930.     //  JoystickView listener
  931.     // *******************************
  932.     private JoystickMovedListener _listener = new JoystickMovedListener() {
  933.         @Override
  934.         public void OnMoved(int x, int y) {
  935.             thrustTemp = fromProgressToRange(y, THRUST_MIN, THRUST_MAX);
  936.             rudderTemp = fromProgressToRange(x, RUDDER_MIN,RUDDER_MAX);
  937.             Log.i(logTag,"Y:" + y + "\tX:" + x);
  938.             Log.i(logTag, "Thrust" + thrustTemp + "\t Rudder" + rudderTemp);
  939.  
  940.         }
  941.  
  942.         @Override
  943.         public void OnReleased() {
  944.  
  945.         }
  946.  
  947.         @Override
  948.         public void OnReturnedToCenter() {
  949.  
  950.         }
  951.     };
  952.  
  953.     public void dialogClose()
  954.     {
  955.         if (getBoatType() == true) {
  956.             //log.append("asdf");
  957.  
  958.             //waypoint on click listener
  959.             /*
  960.              * if the add waypoint button is pressed and new marker where ever they click
  961.              */
  962.  
  963.             mv.setOnTouchListener(new View.OnTouchListener() {
  964.                 @Override
  965.                 public boolean onTouch(View v, MotionEvent event) {
  966.                     if (waypointButton.isChecked()) {
  967.  
  968.                         //Projection proj = ((MapView) v).getProjection();
  969.                         Projection proj = new Projection((MapView)v);
  970.  
  971.                         //Matrix mRotate = proj.getRotationMatrix();
  972.                         Matrix mRotate = new Matrix();
  973.                         mRotate.postRotate(mv.getMapOrientation());
  974.                         Matrix invRotate = new Matrix();
  975.                         mRotate.invert(invRotate);
  976.                         double rX, rY, w;
  977.                         float[] array = new float[9];
  978.                         invRotate.getValues(array);
  979.  
  980.  
  981.                         ILatLng touchedloc = proj.fromPixels(event.getX(), event.getY());
  982. //                        rX = touchedloc.getLatitude() * array[0] + touchedloc.getLongitude() * array[1] + 0 * array[2];
  983. //                        rY = touchedloc.getLatitude() * array[3] + touchedloc.getLongitude() * array[4] + 0 * array[5];
  984. //                        w = touchedloc.getLatitude() * array[6] + touchedloc.getLongitude() * array[7] + 1 * array[8];
  985. //                        LatLng wpLoc = new LatLng(rX, rY);
  986.                         LatLng wpLoc = new LatLng(touchedloc.getLatitude(), touchedloc.getLongitude());
  987.  
  988.                         mv.addMarker(new Marker("", "", wpLoc));
  989.                         waypointList.add(wpLoc);
  990.                         wpstirng = wpLoc.toString();
  991.                         //SendEmail();
  992.                         markerList.add(new Marker("", "", wpLoc));
  993.  
  994.                         Log.i(logTag, "Waypoint "+ wpLoc);
  995.                     }
  996.                     return false;
  997.                 }
  998.  
  999.             });
  1000.  
  1001.             /*
  1002.              * If they press delete wayponts delete all markers off the map and delete waypoints
  1003.              */
  1004.             deleteWaypoint.setOnClickListener(new View.OnClickListener() {
  1005.                 public void onClick(View v) {
  1006.  
  1007.                     // ConnectScreen.boat.cancelWaypoint)
  1008.                     stopWaypoints = true;
  1009.                     //mv.clear();
  1010.                     //mv.removeMarkers(markerList);
  1011.                     waypointList.clear();
  1012.                     isCurrentWaypointDone = true;
  1013.  
  1014.                     try {
  1015.                         mv.clear();
  1016.                         LatLng curLoc = new LatLng(latlongloc.latitudeValue(SI.RADIAN) * 180 / Math.PI, latlongloc.longitudeValue(SI.RADIAN) * 180 / Math.PI);
  1017.                         boat2 = new Marker(currentBoat.getIpAddress().toString(), "Boat", curLoc);
  1018.                         boat2.setIcon(new Icon(getResources().getDrawable(R.drawable.pointarrow)));
  1019.                         boat2.setPoint(curLoc);
  1020.                         mv.animate();
  1021.                         mv.addMarker(boat2);
  1022.                     } catch (Exception e) {
  1023.                         boat2 = new Marker(currentBoat.getIpAddress().toString(), "Boat", new LatLng(pHollowStartingPoint.getLatitude(), pHollowStartingPoint.getLongitude()));
  1024.                     }
  1025.                     System.out.println("called delete");
  1026.                 }
  1027.             });
  1028.  
  1029.  
  1030.             networkThread = new NetworkAsync().execute(); //launch networking asnyc task
  1031.  
  1032.         }
  1033.         else if (getBoatType() == false) {
  1034.             log.append("Simulated Boat");
  1035.             ipAddressBox.setText("Simulated Phone");
  1036.             simulatedBoat();
  1037.         }
  1038.         else
  1039.         {
  1040.             log.append("fail");
  1041.         }
  1042.  
  1043.         try {
  1044.             //boat2 = new Marker(currentBoat.getIpAddress().toString(), "Boat", new LatLng(pHollowStartingPoint.getLatitude(), pHollowStartingPoint.getLongitude()));
  1045.             boat2 = new Marker("Boat", "Boat", new LatLng(pHollowStartingPoint.getLatitude(), pHollowStartingPoint.getLongitude()));
  1046.             mv.addMarker(boat2);
  1047.             mv.setCenter(new ILatLng() {
  1048.                 @Override
  1049.                 public double getLatitude() {
  1050.                     return pHollowStartingPoint.getLatitude();
  1051.                 }
  1052.  
  1053.                 @Override
  1054.                 public double getLongitude() {
  1055.                     return pHollowStartingPoint.getLongitude();
  1056.                 }
  1057.  
  1058.                 @Override
  1059.                 public double getAltitude() {
  1060.                     return 0;
  1061.                 }
  1062.             });
  1063.         }
  1064.         catch(Exception e)
  1065.         {
  1066.  
  1067.         }
  1068.     }
  1069.  
  1070.     @Override
  1071.     public void onPause() {
  1072.         super.onPause();
  1073.         // turns the thrust and rudder off when you pause the activity
  1074.        // thrust.setProgress(0);
  1075.         //rudder.setProgress(50);
  1076.         //networkThread.cancel(true);
  1077.     }
  1078.  
  1079. //    @Override
  1080. //    public void onResume() {
  1081. //        super.onResume();
  1082. //        //Intent intent = new Intent(this, TeleOpPanel.class);
  1083. //        //startActivity(intent);
  1084. //        if (networkThread.isCancelled()) //figure out how to resume asnyc task?
  1085. //        {
  1086. //            //    networkThread.execute();
  1087. //        }
  1088. //    }
  1089.  
  1090.     public static boolean validIP(String ip) {
  1091.         if (ip == null || ip == "")
  1092.             return false;
  1093.         ip = ip.trim();
  1094.         if ((ip.length() < 6) & (ip.length() > 15))
  1095.             return false;
  1096.  
  1097.         try {
  1098.             Pattern pattern = Pattern
  1099.                     .compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
  1100.             Matcher matcher = pattern.matcher(ip);
  1101.             return matcher.matches();
  1102.         } catch (PatternSyntaxException ex) {
  1103.             return false;
  1104.         }
  1105.     }
  1106.  
  1107.     public void updateVelocity(Boat a) { //taken right from desktop client for updating velocity
  1108.         // ConnectScreen.boat.setVelocity(thrust.getProgress(),
  1109.         // rudder.getProgress());
  1110.         if (a.returnServer() != null) {
  1111.             //Twist twist = new Twist();
  1112.             twist.dx(thrustTemp >= -1 & thrustTemp <= 1 ? thrustTemp : 0);
  1113.             if (Math.abs(rudderTemp - 0) < .05) {
  1114.                 tempThrustValue = 0;
  1115.                 twist.drz(fromProgressToRange((int) tempThrustValue, RUDDER_MIN,
  1116.                         RUDDER_MAX));
  1117.  
  1118.             } else {
  1119.                 twist.drz(rudderTemp >= -1 & rudderTemp <= 1 ? rudderTemp : 0);
  1120.             }
  1121.             a.returnServer().setVelocity(twist, null);
  1122.         }
  1123.     }
  1124.  
  1125.     /*
  1126.      * Rotate the bitmap
  1127.      */
  1128.     public static Bitmap RotateBitmap(Bitmap source, float angle)
  1129.     {
  1130.         Matrix matrix = new Matrix();
  1131.         matrix.postRotate(angle);
  1132.         return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
  1133.     }
  1134.  
  1135.     /*
  1136.      * this async task handles all of the networking on the boat since networking has to be done on
  1137.      * a different thread and since gui updates have to be updated on the main thread ....
  1138.      */
  1139.  
  1140.     private class NetworkAsync extends AsyncTask<String, Integer, String> {
  1141.         long oldTime = 0;
  1142.         long oldTime1 = 0;
  1143.         String tester = "done";
  1144.         boolean connected = false;
  1145.         boolean firstTime = true;
  1146.  
  1147.  
  1148.         @Override
  1149.         protected void onPreExecute()
  1150.         {
  1151.  
  1152.         }
  1153.         @Override
  1154.         protected String doInBackground(String... arg0) {
  1155. //            if (currentBoat == null)
  1156. //            {
  1157. //                currentBoat = new Boat();
  1158. //            }
  1159.  
  1160.         //    offlineMapDownloader.addOfflineMapDownloaderListener(this);
  1161. //            PoseListener pl = new PoseListener() { //gets the location of the boat
  1162. //                public void receivedPose(UtmPose upwcs) {
  1163. //
  1164. //                    UtmPose _pose = upwcs.clone();
  1165. //                    {
  1166. //                        xValue = _pose.pose.getX();
  1167. //                        yValue = _pose.pose.getY();
  1168. //                        zValue = _pose.pose.getZ();
  1169. //                        rotation = String.valueOf(Math.PI / 2
  1170. //                                - _pose.pose.getRotation().toYaw());
  1171. //                        rot =  Math.PI/2 - _pose.pose.getRotation().toYaw();
  1172. //
  1173. //                        zone = String.valueOf(_pose.origin.zone);
  1174. //
  1175. //                        latlongloc = UTM.utmToLatLong(UTM.valueOf(
  1176. //                                        _pose.origin.zone, 'T', _pose.pose.getX(),
  1177. //                                        _pose.pose.getY(), SI.METER),
  1178. //                                ReferenceEllipsoid.WGS84);
  1179. //
  1180. //                        //Log.i(logTag, "rot:" + rot);
  1181. //                    }
  1182. //                }
  1183. //            };
  1184. //
  1185. //            currentBoat.returnServer().addPoseListener(pl, null);
  1186.             testWaypointListener();
  1187.  
  1188.  
  1189.  
  1190.  
  1191. //            final SensorListener sensorListener = new SensorListener() {
  1192. //                @Override
  1193. //                public void receivedSensor(SensorData sensorData) {
  1194. //                    Data = sensorData;
  1195. //
  1196. //                    sensorV = Arrays.toString(Data.data);
  1197. //                    sensorV = sensorV.substring(1, sensorV.length()-1);
  1198. //                    sensorReady = true;
  1199. //                    //Log.i("Platypus","Get sensor Data");
  1200. //                }
  1201. //            };
  1202. //
  1203. //            currentBoat.returnServer().getNumSensors(new FunctionObserver<Integer>() {
  1204. //                @Override
  1205. //                public void completed(Integer num) {
  1206. //                    Log.i(logTag, "Sensor Number:" + Integer.toString(num));
  1207. //                    for (channel = 0; channel < num; channel++) {
  1208. //                        currentBoat.returnServer().addSensorListener(channel, sensorListener, null);
  1209. //                    }
  1210. ////                    currentBoat.returnServer().addSensorListener(4, sensorListener, new FunctionObserver<Void>() {
  1211. ////                        @Override
  1212. ////                        public void completed(Void aVoid) {
  1213. ////                            Log.i(logTag, "Adding battery listener");
  1214. ////                        }
  1215. ////
  1216. ////                        @Override
  1217. ////                        public void failed(FunctionError functionError) {
  1218. ////
  1219. ////                        }
  1220. ////                    });
  1221. //                }
  1222. //
  1223. //                @Override
  1224. //                public void failed(FunctionError functionError) {
  1225. //
  1226. //                }
  1227. //            });
  1228.  
  1229.             // For test, comment this when using for real implementation
  1230.             //publishProgress();
  1231.             // setVelListener();
  1232.             // InitSensorData();
  1233.             while (true) { //constantly looping
  1234.                 if (currentBoat != null) {
  1235.                     if (System.currentTimeMillis() % 100 == 0
  1236.                             && oldTime != System.currentTimeMillis()) {
  1237.  
  1238.                         counter++; // if counter == 10 (1000ms), update sensor value
  1239.                         if (currentBoat.isConnected() == true) {
  1240.                             connected = true;
  1241.                             //sensorReady = true;
  1242.                         }
  1243.                         if (currentBoat.isConnected() == false) {
  1244.                             connected = false;
  1245.                         }
  1246.  
  1247.                         if (old_thrust != thrustTemp) { //update velocity
  1248.                             updateVelocity(currentBoat);
  1249.                         }
  1250.  
  1251.                         if (old_rudder != rudderTemp) { //update rudder
  1252.                             updateVelocity(currentBoat);
  1253.                         }
  1254.  
  1255. //                    }
  1256.                         //make this a method
  1257.                         if (stopWaypoints == true) {
  1258.                             currentBoat.returnServer().stopWaypoints(null);
  1259.                             stopWaypoints = false;
  1260.                         }
  1261.  
  1262.  
  1263.  
  1264.                         old_thrust = thrustTemp;
  1265.                         old_rudder = rudderTemp;
  1266.                         oldTime = System.currentTimeMillis();
  1267.  
  1268.  
  1269.  
  1270.                         publishProgress();
  1271.  
  1272.                     }
  1273. //
  1274.                 }
  1275.             }
  1276.  
  1277.  
  1278.         }
  1279.  
  1280.         @Override
  1281.         protected void onProgressUpdate(Integer... result) {
  1282.  
  1283.             //cameraStream.setImageBitmap(currentImage);
  1284.             try
  1285.             {
  1286.                 Projection mvproj = mv.getProjection();
  1287.                 int size = mvproj.getHalfWorldSize();
  1288.                 int right = mvproj.getCenterX();
  1289.                 int top = mvproj.getCenterY();
  1290.                 ILatLng Icomp = mvproj.fromPixels(2084, 112);
  1291.                 LatLng comp = new LatLng(Icomp.getLatitude(),Icomp.getLongitude());
  1292.                 //compass.setPoint(comp);
  1293.  
  1294.                 LatLng curLoc = new LatLng(latlongloc.latitudeValue(SI.RADIAN) * 180 / Math.PI, latlongloc.longitudeValue(SI.RADIAN) * 180 / Math.PI);
  1295.                 float degree = (float)(rot * 180 /Math.PI);  // degree is -90 to 270
  1296.                 degree = (degree < 0 ? 360 + degree : degree); // degree is 0 to 360
  1297.  
  1298.                 float bias = mv.getMapOrientation(); // bias is the map orirentation
  1299.                 // Using bitmap to make marker rotatable.
  1300.                 Bitmap boatarrow = RotateBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pointarrow), degree + bias);
  1301.                 Drawable d = new BitmapDrawable(getResources(),boatarrow);
  1302.                 boat2.setDescription(curLoc.toString());
  1303.                 boat2.setIcon(new Icon(d));
  1304.                 boat2.setPoint(curLoc);
  1305.  
  1306.                 //mvproj.toMapPixels(curLoc,null);
  1307.  
  1308.                // boat2.setRelatedObject(mv);
  1309.                //Log.i(logTag, "Compass " + comp);
  1310.  
  1311.                 mv.animate();
  1312.  
  1313.  
  1314.             if (firstTime == true) {
  1315.                 try {
  1316.                     mv.getController().setCenter(new ILatLng() {
  1317.                         @Override
  1318.                         public double getLatitude() {
  1319.                             return latlongloc.latitudeValue(SI.RADIAN) * 180 / Math.PI;
  1320.  
  1321.                         }
  1322.  
  1323.                         @Override
  1324.                         public double getLongitude() {
  1325.                             return latlongloc.longitudeValue(SI.RADIAN) * 180 / Math.PI;
  1326.  
  1327.                         }
  1328.  
  1329.                         @Override
  1330.                         public double getAltitude() {
  1331.                             return 0;
  1332.                         }
  1333.                     });
  1334.                     //mv.addMarker(compass);
  1335.                     mv.animate();
  1336.                     firstTime = false;
  1337.  
  1338.                 } catch (Exception e) {
  1339.                     firstTime = true; //for false/fake lat long values until the phone gets real location values
  1340.                 }
  1341.             }
  1342.  
  1343.  
  1344.  
  1345.         }
  1346.             catch(Exception e) {
  1347.  
  1348.             }
  1349.  
  1350.  
  1351.  
  1352.         if (connected == true) {
  1353.             ipAddressBox.setBackgroundColor(Color.GREEN);
  1354.         }
  1355.         if (connected == false) {
  1356.             ipAddressBox.setBackgroundColor(Color.RED);
  1357.         }
  1358.  
  1359.  
  1360.  
  1361.         if(sensorReady == true) {
  1362.             sensorvalueButton.setClickable(sensorReady);
  1363.             sensorvalueButton.setTextColor(Color.BLACK);
  1364.             sensorvalueButton.setText("Show SensorData");
  1365.  
  1366.  
  1367.  
  1368.             if(Data.channel == 4){
  1369.                 String[] batteries = sensorV.split(",");
  1370.                 battery.setText(batteries[0]);
  1371.  
  1372.             }
  1373.  
  1374.             if (sensorvalueButton.isChecked()) {
  1375.               //  sensorValueBox.setBackgroundColor(Color.GREEN);
  1376.  
  1377.                 switch (Data.channel) {
  1378.                     case 4:
  1379. //                        String[] batteries = sensorV.split(",");
  1380. //                        battery.setText(batteries[0]);
  1381.                         break;
  1382.                     case 1:
  1383.                         sensorData1.setText(sensorV);
  1384.                         sensorType1.setText(Data.type+"\n"+unit(Data.type));
  1385.  
  1386.                         break;
  1387.                     case 2:
  1388.                         sensorData2.setText(sensorV);
  1389.                         sensorType2.setText(Data.type+ "\n"+unit(Data.type));
  1390.  
  1391.                         break;
  1392.                     case 3:
  1393.                         sensorData3.setText(sensorV);
  1394.                         sensorType3.setText(Data.type+ "\n"+unit(Data.type));
  1395.  
  1396.                         break;
  1397.                     case 9:
  1398.                         break;
  1399.                     default:
  1400.                         sensorData1.setText("Waiting");
  1401.                         sensorData2.setText("Waiting");
  1402.                         sensorData3.setText("Waiting");
  1403.                 }
  1404.  
  1405.             }
  1406.             if (!sensorvalueButton.isChecked()) {
  1407.                 //sensorV = "";
  1408.                 sensorData1.setText("----");
  1409.                 sensorData2.setText("----");
  1410.                 sensorData3.setText("----");
  1411.                 //sensorValueBox.setBackgroundColor(Color.DKGRAY);
  1412.             }
  1413.         }
  1414.         else{
  1415.             sensorvalueButton.setText("Sensor Unavailable");
  1416.             sensorData1.setText("----");
  1417.             sensorData2.setText("----");
  1418.             sensorData3.setText("----");
  1419.         }
  1420. //********************************//
  1421. // Adding Joystick move listener//
  1422. // ******************************//
  1423.         joystick.setOnJostickMovedListener(_listener);
  1424.  
  1425.         DecimalFormat velFormatter = new DecimalFormat("####.###");
  1426.  
  1427.         //thrustTemp = fromProgressToRange(thrust.getProgress(), THRUST_MIN, THRUST_MAX);
  1428.        // rudderTemp = fromProgressToRange(rudder.getProgress(), RUDDER_MIN, RUDDER_MAX);
  1429.         thrustProgress.setText(velFormatter.format(thrustTemp * 100.0) + "%");
  1430.         rudderProgress.setText(velFormatter.format(rudderTemp * -100.0) + "%");
  1431.  
  1432.         log.setText("Waypoint Status: \n" + boatwaypoint);
  1433.         autoBox.setChecked(isAutonomous);
  1434.  
  1435.  
  1436.  
  1437.     }
  1438. }
  1439.  
  1440.     public void simulatedBoat() {
  1441. //        boat2 = map.addMarker(new MarkerOptions().anchor(.5f, .5f) //add boat to panther hollow
  1442. //                .rotation(270).title("Boat 1")
  1443. //                .snippet("IP Address: 192.168.1.1")
  1444. //                .position(pHollowStartingPoint).title("Boat 1")
  1445. //                .snippet("127.0.0.1 (localhost)")
  1446. //                        //.icon(BitmapDescriptorFactory.fromResource(R.drawable.airboat))
  1447. //                .flat(true));
  1448. //
  1449. //        lat = pHollowStartingPoint.latitude;
  1450. //        lon = pHollowStartingPoint.longitude;
  1451. //        map.setMyLocationEnabled(true);
  1452. //        map.moveCamera(CameraUpdateFactory.newLatLngZoom(pHollowStartingPoint,
  1453. //                15));
  1454. //        map.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
  1455. //
  1456. //        boat2.setRotation((float) (heading * (180 / Math.PI)));
  1457. //        handlerRudder.post(new Runnable() { //control the boat
  1458. //            @Override
  1459. //            public void run() {
  1460. //                if (thrust.getProgress() > 0) {
  1461. //                    lat += Math.cos(heading) * (thrust.getProgress() - 50)
  1462. //                            * .0000001;
  1463. //                    lon += Math.sin(heading) * (thrust.getProgress())
  1464. //                            * .0000001;
  1465. //                    heading -= (rudder.getProgress() - 50) * .001;
  1466. //                    boat2.setRotation((float) (heading * (180 / Math.PI)));
  1467. //                }
  1468. //                boat2.setPosition(new LatLng(lat, lon));
  1469. //                handlerRudder.postDelayed(this, 200);
  1470. //            }
  1471. //        });
  1472.     }
  1473.     private String unit(VehicleServer.SensorType Type){
  1474.         String unit="";
  1475.         if(Type.toString().equalsIgnoreCase("ATLAS_PH")){
  1476.             unit = "pH";
  1477.         }
  1478.         if(Type.toString().equalsIgnoreCase("ATLAS_DO")){
  1479.             unit = "mg/L";
  1480.         }
  1481.         if(Type.toString().equalsIgnoreCase("ES2")){
  1482.             unit = "EC(µS/cm)\n" +
  1483.                     "TE(°C)";
  1484.         }
  1485.         if(Type.toString().equalsIgnoreCase("HDS_DEPTH")){
  1486.             unit = "m";
  1487.         }
  1488.  
  1489.  
  1490.         return unit;
  1491.     }
  1492.  
  1493.     public void setVelListener() {
  1494.         currentBoat.returnServer().addVelocityListener(
  1495.                 new VelocityListener() {
  1496.                     public void receivedVelocity(Twist twist) {
  1497.                         thrust.setProgress(fromRangeToProgress(twist.dx(),
  1498.                                 THRUST_MIN, THRUST_MAX));
  1499.                         rudder.setProgress(fromRangeToProgress(twist.drz(),
  1500.                                 RUDDER_MIN, RUDDER_MAX));
  1501.                     }
  1502.                 }, null);
  1503.  
  1504.     }
  1505.  
  1506.     // Converts from progress bar value to linear scaling between min and
  1507. // max
  1508.     private double fromProgressToRange(int progress, double min, double max) {
  1509.         return ((max - min) * ((double) progress) / 20.0);
  1510.     }
  1511.  
  1512.     // Converts from progress bar value to linear scaling between min and
  1513. // max
  1514.     private int fromRangeToProgress(double value, double min, double max) {
  1515.         return (int) (20.0 * (value ) / (max - min));
  1516.     }
  1517.  
  1518.     /* accelerometer controls */
  1519.     @Override
  1520.     public void onAccuracyChanged(Sensor sensor, int accuracy) {
  1521.  
  1522.     }
  1523.  
  1524.     @Override
  1525.     public void onSensorChanged(SensorEvent sensorEvent) {
  1526.         Sensor mySensor = sensorEvent.sensor;
  1527.         if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
  1528.             float x = sensorEvent.values[0];
  1529.             float y = sensorEvent.values[1];
  1530.             float z = sensorEvent.values[2];
  1531.  
  1532.             long curTime = System.currentTimeMillis();
  1533.  
  1534. //            if (tiltButton.isChecked()) {
  1535. //                if ((curTime - lastUpdate) > 100) {
  1536. //                    long diffTime = (curTime - lastUpdate);
  1537. //                    lastUpdate = curTime;
  1538. //                    float speed = Math
  1539. //                            .abs(x + y + z - last_x - last_y - last_z)
  1540. //                            / diffTime * 10000;
  1541. //
  1542. //                    if (speed > SHAKE_THRESHOLD) {
  1543. //                    }
  1544. //
  1545. //                    last_x = y; // rudder switching x and z for tesing orientation
  1546. //                    last_y = x;
  1547. //                    last_z = z; // thrust
  1548. //                    // test.setText("x: " + last_x + "y: " + last_y + "z: "
  1549. //                    // + last_z);
  1550. //
  1551. //                    //updateViaAcceleration(last_x, last_y, last_z);
  1552. //                }
  1553. //            }
  1554.         }
  1555.     }
  1556.  
  1557.     public void updateViaAcceleration(float xval, float yval, float zval) { //update the thrust via accelerometers
  1558.         if (Math.abs(tempX - last_x) > 2.5) {
  1559.  
  1560.             if (last_x > 2) {
  1561.                 thrust.setProgress(thrust.getProgress() - 3);
  1562.             }
  1563.             if (last_x < 2) {
  1564.                 thrust.setProgress(thrust.getProgress() + 3);
  1565.             }
  1566.         }
  1567.         if (Math.abs(tempY - last_y) > 1) {
  1568.             if (last_y > 2) {
  1569.                 rudder.setProgress(rudder.getProgress() - 3);
  1570.             }
  1571.             if (last_y < -2) {
  1572.                 rudder.setProgress(rudder.getProgress() + 3);
  1573.             }
  1574.         }
  1575.     }
  1576.  
  1577.     public void addWayPointFromMap() {
  1578.         // when you click you make utm pose... below is fake values
  1579.         Pose3D pose = new Pose3D(1, 1, 0, 0.0, 0.0, 10);
  1580.         Utm origin = new Utm(17, true);
  1581.         // ConnectScreen.boat.addWaypoint(pose, origin);
  1582.         UtmPose[] wpPose = new UtmPose[1];
  1583.         wpPose[0] = new UtmPose(pose, origin);
  1584.         currentBoat.returnServer().startWaypoints(wpPose,
  1585.                 "POINT_AND_SHOOT", new FunctionObserver<Void>() {
  1586.                     public void completed(Void v) {
  1587.                         //log.setText("completed"); UNCOMMENT THESE
  1588.                     }
  1589.  
  1590.                     public void failed(FunctionError fe) {
  1591.                         ///log.setText("failed");
  1592.                     }
  1593.                 });
  1594.  
  1595.     }
  1596.  
  1597.     public LatLng convertUtmLatLng(Pose3D _pose, Utm _origin) {
  1598.         LatLong temp = UTM
  1599.                 .utmToLatLong(
  1600.                         UTM.valueOf(_origin.zone, 'T', _pose.getX(),
  1601.                                 _pose.getY(), SI.METER),
  1602.                         ReferenceEllipsoid.WGS84);
  1603.         return new LatLng(temp.latitudeValue(SI.RADIAN),
  1604.                 temp.longitudeValue(SI.RADIAN));
  1605.     }
  1606.  
  1607.     public UtmPose convertLatLngUtm(ILatLng point) {
  1608.  
  1609.         UTM utmLoc = UTM.latLongToUtm(LatLong.valueOf(point.getLatitude(),
  1610.                 point.getLongitude(), NonSI.DEGREE_ANGLE), ReferenceEllipsoid.WGS84);
  1611.  
  1612.         // Convert to UTM data structure
  1613.         Pose3D pose = new Pose3D(utmLoc.eastingValue(SI.METER), utmLoc.northingValue(SI.METER), 0.0, 0, 0, 0);
  1614.         Utm origin = new Utm(utmLoc.longitudeZone(), utmLoc.latitudeZone() > 'O');
  1615.         UtmPose utm = new UtmPose(pose, origin);
  1616.         return utm;
  1617.     }
  1618.  
  1619.  
  1620.     //  public void viewCamera()
  1621. //  {
  1622. //      ConnectScreen.boat.returnServer().addImageListener(new ImageListener() {
  1623. //
  1624. //            public void receivedImage(byte[] imageData) {
  1625. //                // Take a picture, and put the resulting image into the panel
  1626. //                try {
  1627. //                  Bitmap image1 = BitmapFactory.decodeByteArray(imageData, 0, 15);
  1628. //                    BufferedImage image = ImageIO.read(new java.io.ByteArrayInputStream(imageData));
  1629. //                    if (image != null) {
  1630. //                        Image scaledImage = image.getScaledInstance(pictureLabel.getWidth(), pictureLabel.getHeight(), Image.SCALE_DEFAULT);
  1631. //                        pictureLabel.setIcon(new ImageIcon(scaledImage));
  1632. //                        CameraPanel.this.repaint();
  1633. //                    } else {
  1634. //                        System.err.println("Failed to decode image.");
  1635. //                    }
  1636. //                } catch (IOException ex) {
  1637. //                    System.err.println("Failed to decode image: " + ex);
  1638. //                }
  1639. //
  1640. //            }
  1641. //        }, null);
  1642.     public void testCamera() {
  1643.         //log.setText("test camera");
  1644.         currentBoat.returnServer().addImageListener(new ImageListener() {
  1645.             public void receivedImage(byte[] imageData) {
  1646.                 // Take a picture, and put the resulting image into the panel
  1647.                 //log.setText("image taken");
  1648.  
  1649.                 try {
  1650.                     Bitmap image1 = BitmapFactory.decodeByteArray(imageData, 0, 15);
  1651.                     if (image1 != null) {
  1652.                         // a++;
  1653.                         //System.out.println("image made");
  1654.                         currentImage = image1;
  1655.  
  1656.                     }
  1657.                 } catch (Exception e) {
  1658.                     //log.setText(e.toString()); uncomment this
  1659.                     e.printStackTrace();
  1660.                 }
  1661.             }
  1662.         }, null);
  1663.     }
  1664.  
  1665.     public void connectBox()
  1666.     {
  1667.         final Dialog dialog = new Dialog(context);
  1668.         dialog.setContentView(R.layout.connectdialog);
  1669.         ipAddress = (EditText) dialog.findViewById(R.id.ipAddress1);
  1670.  
  1671.         Button submitButton = (Button) dialog.findViewById(R.id.submit);
  1672.         simvsact = (RadioGroup) dialog.findViewById(R.id.simvsactual);
  1673.         actualBoat = (RadioButton) dialog.findViewById(R.id.actualBoatRadio);
  1674.         simulation = (RadioButton) dialog.findViewById(R.id.simulationRadio);
  1675.  
  1676.         direct = (RadioButton) dialog.findViewById(R.id.wifi);
  1677.         reg = (RadioButton) dialog.findViewById(R.id.reg);
  1678.         ipAddress.setText("tunnel.senseplatypus.com");
  1679.  
  1680.         direct.setOnClickListener(new OnClickListener() {
  1681.             @Override
  1682.             public void onClick(View v) {
  1683.                 if(direct.isChecked()){
  1684.                     ipAddress.setText("192.168.1.");
  1685.                 }
  1686.             }
  1687.         });
  1688.         reg.setOnClickListener(new OnClickListener() {
  1689.             @Override
  1690.             public void onClick(View v) {
  1691.                 if (reg.isChecked())
  1692.                 {
  1693.                     ipAddress.setText("tunnel.senseplatypus.com");
  1694.                 }
  1695.                 else
  1696.                 {
  1697.                     ipAddress.setText("192.168.1.");
  1698.                 }
  1699.             }
  1700.         });
  1701.         if (ipAddress.getText() == null || ipAddress.getText().equals("") || ipAddress.getText().length()==0)
  1702.         {
  1703.             ipAddressBox.setText("IP Address: 127.0.0.1 (localhost)");
  1704.         }
  1705.         else {
  1706.             ipAddressBox.setText("IP Address: " + ipAddress.getText());
  1707.         }
  1708.  
  1709.  
  1710.         submitButton.setOnClickListener(new OnClickListener() {
  1711.             @Override
  1712.             public void onClick(View v) {
  1713.                 // int selectedId = simvsact.getCheckedRadioButtonId();
  1714.                 //int selectedOption = actvsim.getCheckedRadioButtonId();
  1715.                 //log.append("asdf" + selectedOption);
  1716. //                if (boat2 != null) {
  1717.                     //boat2.remove();
  1718. //                }
  1719.                 markerList = new ArrayList<Marker>();
  1720.                 actual = actualBoat.isChecked();
  1721.  
  1722.                 textIpAddress = ipAddress.getText().toString();
  1723.                 System.out.println("asdfasdfasdf");
  1724.                 System.out.println("IP Address entered is: " + textIpAddress);
  1725.                 if (direct.isChecked()) {
  1726.                     if (ipAddress.getText() == null || ipAddress.getText().equals("")) {
  1727.                         address = CrwNetworkUtils.toInetSocketAddress("127.0.0.1" + ":11411");
  1728.                     }
  1729.                     address = CrwNetworkUtils.toInetSocketAddress(textIpAddress + ":11411");
  1730.                    // address = CrwNetworkUtils.toInetSocketAddress(textIpAddress + ":6077");
  1731. //                    log.append("\n" + address.toString());
  1732.                     //currentBoat = new Boat(address);
  1733.                     currentBoat.setAddress(address);
  1734.                 }
  1735.                 else if(reg.isChecked())
  1736.                 {
  1737.                     Log.i(logTag,"finding ip");
  1738.                     FindIP();
  1739.                 }
  1740.                 mv.clear();
  1741.                 dialog.dismiss();
  1742.                 dialogClose();
  1743.             }
  1744.         });
  1745.  
  1746.         dialog.show();
  1747.  
  1748.     }
  1749.  
  1750.     public static InetSocketAddress getAddress()
  1751.     {
  1752.         return address;
  1753.     }
  1754.     public static String getIpAddress() {
  1755.         return textIpAddress;
  1756.     }
  1757.  
  1758.     public static boolean getBoatType() {
  1759.         return actual;
  1760.     }
  1761.     public void waypointListenerTest()
  1762.     {
  1763.         currentBoat.returnServer().addWaypointListener(new WaypointListener() {
  1764.             @Override
  1765.             public void waypointUpdate(WaypointState waypointState) {
  1766.                 System.out.println("waypontstate: " + waypointState.toString());
  1767.             }
  1768.         },null);
  1769.     }
  1770.     public void testWaypointListener()
  1771.     {
  1772.         //this gets called on doInBackground() in the async task
  1773.         currentBoat.returnServer().addWaypointListener(new WaypointListener() {
  1774.             public void waypointUpdate(WaypointState ws) {
  1775.                 boatwaypoint = ws.toString();
  1776. //                currentBoat.returnServer().isAutonomous(new FunctionObserver<Boolean>() {
  1777. //                    @Override
  1778. //                    public void completed(Boolean aBoolean) {
  1779. //                        isAutonomous = aBoolean;
  1780. //                        Log.i(logTag, "isAutonomous: "+ isAutonomous);
  1781. //                    }
  1782. //
  1783. //                    @Override
  1784. //                    public void failed(FunctionError functionError) {
  1785. //
  1786. //                    }
  1787.                 //});
  1788.                 //System.out.println(boatwaypoint);
  1789.             }
  1790.         }, null);
  1791.     }
  1792.     private void checkAndSleepForCmd() {
  1793.         if (lastTime >= 0) {
  1794.             long timeGap = 1000 - (System.currentTimeMillis() - lastTime);
  1795.             if (timeGap > 0) {
  1796.                 try {
  1797.                     Thread.sleep(timeGap);
  1798.                 } catch (InterruptedException ex) {
  1799.                 }
  1800.             }
  1801.         }
  1802.         lastTime = System.currentTimeMillis();
  1803.     }
  1804.     public void fromFiletoWPList() throws IOException
  1805.     {
  1806.         //code for opening window for meantime have tmep folder with one file it accepts for wp list
  1807.         File readFile = new File("");
  1808.         Scanner fileReader = new Scanner(readFile);
  1809.         //set delimeter
  1810.         //parse text into latlong
  1811.         //waypointList.add(fileReader.next());
  1812.     }
  1813.  
  1814.     /* at the moment does not validate files! make sure your waypoint file is correctly matched this will be implemented later..*/
  1815.     public boolean setWaypointsFromFile() throws IOException {
  1816.         File wpFile = null;
  1817.         try {
  1818.             wpFile = new File("./waypoints.txt");
  1819.         }
  1820.         catch(Exception e)
  1821.         {
  1822.             System.out.println(e.toString());
  1823.         }
  1824.         Scanner fileScanner;
  1825.         int valueCounter = 0;
  1826.         //first make sure even number of elements
  1827.  
  1828.         if (wpFile.exists()) {
  1829.             fileScanner = new Scanner(wpFile);
  1830.             //first make sure even number of element
  1831.             while(fileScanner.hasNext())
  1832.             {
  1833.                 try
  1834.                 {
  1835.                     LatLng temp = new LatLng(Double.parseDouble(fileScanner.next()), Double.parseDouble(fileScanner.next()));
  1836.                     waypointList.add(temp);
  1837.                     Marker tempMarker = mv.addMarker(new Marker("","",temp));
  1838.                     markerList.add(tempMarker);
  1839.                 }
  1840.                 catch(Exception e)
  1841.                 {
  1842.                     System.out.println("Invalid LAT/LNG in file");
  1843.                 }
  1844.                 System.out.println(fileScanner.next() + " " + fileScanner.next());
  1845.                 valueCounter+=2;
  1846.             }
  1847.             System.out.println("amount of elements: " + valueCounter);
  1848.             if ((valueCounter % 2) != 0)
  1849.             {
  1850.                 System.out.println("Mismatching lat long vals");
  1851.                 return false;
  1852.             }
  1853.             else
  1854.             {
  1855.                 System.out.println("Valid");
  1856.             }
  1857.         } else
  1858.         {
  1859.             System.out.println("File not found");
  1860.         }
  1861.         return true;
  1862.     }
  1863.  
  1864. //    public void FindIP() {
  1865. //
  1866. //
  1867.  
  1868. //        address = CrwNetworkUtils.toInetSocketAddress(textIpAddress + ":6077");
  1869. //
  1870. //        Thread thread = new Thread() {
  1871. //            public void run() {
  1872. //
  1873. //                currentBoat = new Boat();
  1874. //                UdpVehicleServer tempserver = new UdpVehicleServer();
  1875. //                currentBoat.returnServer().setRegistryService(address);
  1876. //                currentBoat.returnServer().getVehicleServices(new FunctionObserver<Map<SocketAddress, String>>() {
  1877. //                    @Override
  1878. //                    public void completed(Map<SocketAddress, String> socketAddressStringMap) {
  1879. //                        System.out.println("Completed");
  1880. //                        for (Map.Entry<SocketAddress, String> entry : socketAddressStringMap.entrySet()) {
  1881. //
  1882. //
  1883. //                            //newaddressstring = entry.getKey().toString();
  1884. //                            //System.out.println(newaddressstring);
  1885. //                            currentBoat.returnServer().setVehicleService(entry.getKey());
  1886. //
  1887. //                            System.out.println(entry.getKey().toString());
  1888. //                            System.out.println(entry.getValue().toString());
  1889. //
  1890. //                        }
  1891. //                    }
  1892. //
  1893. //                    @Override
  1894. //                    public void failed(FunctionError functionError) {
  1895. //                        System.out.println("No Response");
  1896. //                    }
  1897. //                });
  1898. //                //currentBoat = new Boat(CrwNetworkUtils.toInetSocketAddress(newaddressstring));
  1899. //                //System.out.println("Boat address" + currentBoat.getIpAddress());
  1900. //                // regcheck.show();
  1901. //                //}
  1902. //            }
  1903. //        };
  1904. //
  1905. //        thread.start();
  1906. //        //System.out.println("print here: " + newaddressstring);
  1907. //        //currentBoat = new Boat(CrwNetworkUtils.toInetSocketAddress(newaddressstring));
  1908. //
  1909. //    }
  1910. public void FindIP() {
  1911.  
  1912.  
  1913.  
  1914.  
  1915.     Thread thread = new Thread() {
  1916.  
  1917.         public void run() {
  1918.             address = CrwNetworkUtils.toInetSocketAddress(textIpAddress + ":6077");
  1919.             //address = CrwNetworkUtils.toInetSocketAddress(textIpAddress);
  1920.             //currentBoat = new Boat(pl,null);
  1921.            // currentBoat = new Boat();
  1922.            // UdpVehicleServer tempserver = new UdpVehicleServer();
  1923.             currentBoat.returnServer().setRegistryService(address);
  1924.             currentBoat.returnServer().getVehicleServices(new FunctionObserver<Map<SocketAddress, String>>() {
  1925.                 @Override
  1926.                 public void completed(Map<SocketAddress, String> socketAddressStringMap) {
  1927.                     Log.i(logTag, "Completed");
  1928.                     for (Map.Entry<SocketAddress, String> entry : socketAddressStringMap.entrySet()) {
  1929.                         //newaddressstring = entry.getKey().toString();
  1930.                         //System.out.println(newaddressstring);
  1931.                         // currentBoat.returnServer().setVehicleService(entry.getKey());
  1932. //                        adapter.add(entry);
  1933. //                        adapter.notifyDataSetChanged();
  1934.  
  1935.                         Log.i(logTag, entry.toString());
  1936.                         currentBoat.returnServer().setVehicleService(entry.getKey());
  1937.  
  1938.  
  1939. //
  1940.  
  1941.                     }
  1942. //                    if(currentBoat.isConnected() == true){
  1943. //                        Log.i(logTag, "Connected");
  1944. //                    }
  1945. //                    else{
  1946. //                        Log.i(logTag, "Disconnected");
  1947. //                    }
  1948.                 }
  1949.  
  1950.                 @Override
  1951.                 public void failed(FunctionError functionError) {
  1952.                     Log.i(logTag,"No Response");
  1953.                 }
  1954.             });
  1955.  
  1956.         }
  1957.     };
  1958.     thread.start();
  1959.  
  1960. }
  1961.  
  1962.     public void SendEmail()
  1963.     {
  1964.         Thread thread = new Thread() {
  1965.             public void run() {
  1966.                 Email mail = new Email("platypuslocation@gmail.com", "airboats");
  1967.                 try {
  1968.                     //   mail.sendMail("jeffboat", wpstirng, "shantanu@gmail.com", "platypuslocation@gmail.com");
  1969.                 }
  1970.                 catch(Exception e)
  1971.                 {
  1972.                     System.out.println(e.toString());
  1973.                     System.out.println("fucked up");
  1974.                 }
  1975.  
  1976.             }
  1977.         };
  1978.         thread.start();
  1979.     }
  1980.  
  1981.     public void InitSensorData() {
  1982.         while (currentBoat == null) {
  1983.         }
  1984.  
  1985.         final SensorListener sensorListener = new SensorListener() {
  1986.             @Override
  1987.             public void receivedSensor(SensorData sensorData) {
  1988.  
  1989.                 Data = sensorData;
  1990.                 //data = Data.data;
  1991.                 //channel = Data.channel;
  1992.                 sensorV = Arrays.toString(Data.data);
  1993.                 //sensorV = Integer.toString(Data.channel);
  1994. //                if(Data.toString()==null){
  1995. //                    sensorV = "No sensor value";
  1996. //                }
  1997. //                else {
  1998. //                    sensorV = Data.toString();
  1999. //                }
  2000.             }
  2001.         };
  2002.  
  2003.         //currentBoat.returnServer().getNumSensors(new FunctionObserver<Integer>() {
  2004.         // @Override
  2005.         //  public void completed(Integer numSensors) {
  2006.         //    System.out.println("Sensor num:" + numSensors);
  2007.         //  for (int channel = 0; channel < numSensors; ++channel) {
  2008.         currentBoat.returnServer().addSensorListener(3, sensorListener, new FunctionObserver<Void>() {
  2009.             @Override
  2010.             public void completed(Void aVoid) {
  2011.                 System.out.println("Add Sensorlistener");
  2012.             }
  2013.  
  2014.             @Override
  2015.             public void failed(FunctionError functionError) {
  2016.                 sensorV = "Failed to get sensor value";
  2017.             }
  2018.         });
  2019.     }
  2020.  
  2021.     //  Make return button same as home button
  2022.         @Override
  2023.     public void onBackPressed() {
  2024.         //Log.d("CDA", "onBackPressed Called");
  2025.         Intent setIntent = new Intent(Intent.ACTION_MAIN);
  2026.         setIntent.addCategory(Intent.CATEGORY_HOME);
  2027.         setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  2028.         startActivity(setIntent);
  2029.     }
  2030.  
  2031. }
  2032. //
  2033. //class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement