Advertisement
efisioneto

SIGMA-FF

Oct 23rd, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 33.36 KB | None | 0 0
  1. /*
  2.  
  3.  * Copyright (C) 2014 The Android Open Source Project
  4.  
  5.  *
  6.  
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  
  9.  * you may not use this file except in compliance with the License.
  10.  
  11.  * You may obtain a copy of the License at
  12.  
  13.  *
  14.  
  15.  *      http://www.apache.org/licenses/LICENSE-2.0
  16.  
  17.  *
  18.  
  19.  * Unless required by applicable law or agreed to in writing, software
  20.  
  21.  * distributed under the License is distributed on an "AS IS" BASIS,
  22.  
  23.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24.  
  25.  * See the License for the specific language governing permissions and
  26.  
  27.  * limitations under the License.
  28.  
  29.  */
  30.  
  31.  
  32.  
  33. package com.example.android.bluetoothchat;
  34.  
  35.  
  36.  
  37. import android.app.ActionBar;
  38.  
  39. import android.app.Activity;
  40.  
  41. import android.bluetooth.BluetoothAdapter;
  42.  
  43. import android.bluetooth.BluetoothDevice;
  44.  
  45. import android.content.Intent;
  46.  
  47. import android.graphics.Color;
  48. import android.os.Bundle;
  49.  
  50. import android.os.Handler;
  51.  
  52. import android.os.Message;
  53.  
  54. import android.view.KeyEvent;
  55.  
  56. import android.view.LayoutInflater;
  57.  
  58. import android.view.Menu;
  59.  
  60. import android.view.MenuInflater;
  61.  
  62. import android.view.MenuItem;
  63.  
  64. import android.view.View;
  65.  
  66. import android.view.ViewGroup;
  67.  
  68. import android.view.inputmethod.EditorInfo;
  69.  
  70. import android.widget.ArrayAdapter;
  71.  
  72. import android.widget.Button;
  73.  
  74. import android.widget.EditText;
  75.  
  76. import android.widget.ListView;
  77.  
  78. import android.widget.TextView;
  79.  
  80. import android.widget.Toast;
  81.  
  82.  
  83.  
  84. import androidx.annotation.NonNull;
  85.  
  86. import androidx.annotation.Nullable;
  87.  
  88. import androidx.fragment.app.Fragment;
  89.  
  90. import androidx.fragment.app.FragmentActivity;
  91.  
  92.  
  93.  
  94. import com.example.android.common.logger.Log;
  95.  
  96. //#graphView
  97. import com.jjoe64.graphview.GraphView;
  98. import com.jjoe64.graphview.series.DataPoint;
  99. import com.jjoe64.graphview.series.LineGraphSeries;
  100. import com.jjoe64.graphview.GridLabelRenderer;
  101.  
  102. import java.util.Random;
  103.  
  104.  
  105. /**
  106.  
  107.  * This fragment controls Bluetooth to communicate with other devices.
  108.  
  109.  */
  110.  
  111. public class BluetoothChatFragment extends Fragment{
  112.  
  113.  
  114.     private static final String TAG = "BluetoothChatFragment";
  115.  
  116.  
  117.     // Intent request codes
  118.  
  119.     private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
  120.  
  121.     private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
  122.  
  123.     private static final int REQUEST_ENABLE_BT = 3;
  124.  
  125.  
  126.  
  127.     // Layout Views
  128.  
  129.     private ListView mConversationView;
  130.  
  131.     private EditText mOutEditText;
  132.  
  133.     private Button mSendButton;
  134.  
  135.  
  136.     /**
  137.      * Name of the connected device
  138.      */
  139.  
  140.     private String mConnectedDeviceName = null;
  141.  
  142.  
  143.     /**
  144.      * Array adapter for the conversation thread
  145.      */
  146.  
  147.     private ArrayAdapter<String> mConversationArrayAdapter;
  148.  
  149.  
  150.     /**
  151.      * String buffer for outgoing messages
  152.      */
  153.  
  154.     private StringBuffer mOutStringBuffer;
  155.  
  156.  
  157.     /**
  158.      * Local Bluetooth adapter
  159.      */
  160.  
  161.     private BluetoothAdapter mBluetoothAdapter = null;
  162.  
  163.  
  164.     /**
  165.      * Member object for the chat services
  166.      */
  167.  
  168.     private BluetoothChatService mChatService = null;
  169.  
  170.     private String hexX, hexY;
  171.     public static int  decimalX,decimalY;
  172.     public int i =0;
  173.  
  174.  
  175.  
  176.     @Override
  177.  
  178.     public void onCreate(Bundle savedInstanceState) {
  179.  
  180.         super.onCreate(savedInstanceState);
  181.  
  182.         setHasOptionsMenu(true);
  183.  
  184.         // Get local Bluetooth adapter
  185.  
  186.         mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  187.  
  188.  
  189.         // If the adapter is null, then Bluetooth is not supported
  190.  
  191.         FragmentActivity activity = getActivity();
  192.  
  193.         if (mBluetoothAdapter == null && activity != null) {
  194.  
  195.             Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
  196.  
  197.             activity.finish();
  198.  
  199.         }
  200.         //#graphView https://github.com/jjoe64/GraphView
  201.         //GraphView graph = (GraphView) findViewById(R.id.graph);
  202. //        GraphView graph = (GraphView) findViewById(R.id.graph);
  203. //        initGraph(graph);
  204. //
  205.  
  206.     }
  207.  
  208.     @Override
  209.  
  210.     public void onStart() {
  211.  
  212.         super.onStart();
  213.  
  214.         if (mBluetoothAdapter == null) {
  215.  
  216.             return;
  217.  
  218.         }
  219.  
  220.         // If BT is not on, request that it be enabled.
  221.  
  222.         // setupChat() will then be called during onActivityResult
  223.  
  224.         if (!mBluetoothAdapter.isEnabled()) {
  225.  
  226.             Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  227.  
  228.             startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
  229.  
  230.             // Otherwise, setup the chat session
  231.  
  232.         } else if (mChatService == null) {
  233.  
  234.             setupChat();
  235.  
  236.         }
  237.  
  238.     }
  239.  
  240.  
  241.     @Override
  242.  
  243.     public void onDestroy() {
  244.  
  245.         super.onDestroy();
  246.  
  247.         if (mChatService != null) {
  248.  
  249.             mChatService.stop();
  250.  
  251.         }
  252.  
  253.     }
  254.  
  255.  
  256.  
  257.     @Override
  258.  
  259.     public void onResume() {
  260.  
  261.         super.onResume();
  262.  
  263.  
  264.         // Performing this check in onResume() covers the case in which BT was
  265.  
  266.         // not enabled during onStart(), so we were paused to enable it...
  267.  
  268.         // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
  269.  
  270.         if (mChatService != null) {
  271.  
  272.             // Only if the state is STATE_NONE, do we know that we haven't started already
  273.  
  274.             if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
  275.  
  276.                 // Start the Bluetooth chat services
  277.  
  278.                 mChatService.start();
  279.  
  280.             }
  281.  
  282.         }
  283.  
  284.     }
  285.  
  286.  
  287.     @Override
  288.  
  289.     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
  290.  
  291.                              @Nullable Bundle savedInstanceState) {
  292.  
  293.         return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
  294.  
  295.     }
  296.  
  297.  
  298.     @Override
  299.  
  300.     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
  301.  
  302.         mConversationView = view.findViewById(R.id.in);
  303.  
  304.         mOutEditText = view.findViewById(R.id.edit_text_out);
  305.  
  306.         mSendButton = view.findViewById(R.id.button_send);
  307.  
  308.  
  309.  
  310.     }
  311.  
  312.  
  313.     /**
  314.      * Set up the UI and background operations for chat.
  315.      */
  316.  
  317.     private void setupChat() {
  318.  
  319.         Log.d(TAG, "setupChat()");
  320.  
  321.  
  322.         // Initialize the array adapter for the conversation thread
  323.  
  324.         FragmentActivity activity = getActivity();
  325.  
  326.         if (activity == null) {
  327.  
  328.             return;
  329.  
  330.         }
  331.  
  332.         mConversationArrayAdapter = new ArrayAdapter<>(activity, R.layout.message);
  333.  
  334.  
  335.         mConversationView.setAdapter(mConversationArrayAdapter);
  336.  
  337.  
  338.         // Initialize the compose field with a listener for the return key
  339.  
  340.         mOutEditText.setOnEditorActionListener(mWriteListener);
  341.  
  342.  
  343.         // Initialize the send button with a listener that for click events
  344.  
  345.         mSendButton.setOnClickListener(new View.OnClickListener() {
  346.  
  347.             public void onClick(View v) {
  348.  
  349.                 // Send a message using content of the edit text widget
  350.  
  351.                 View view = getView();
  352.  
  353.                 if (null != view) {
  354.  
  355.                     TextView textView = view.findViewById(R.id.edit_text_out);
  356.  
  357.                     String message = textView.getText().toString();
  358.  
  359.                     sendMessage(message);
  360.  
  361.                 }
  362.  
  363.             }
  364.  
  365.         });
  366.  
  367.  
  368.         // Initialize the BluetoothChatService to perform bluetooth connections
  369.  
  370.         mChatService = new BluetoothChatService(activity, mHandler);
  371.  
  372.  
  373.         // Initialize the buffer for outgoing messages
  374.  
  375.         mOutStringBuffer = new StringBuffer();
  376.  
  377.     }
  378.  
  379.  
  380.     /**
  381.      * Makes this device discoverable for 300 seconds (5 minutes).
  382.      */
  383.  
  384.     private void ensureDiscoverable() {
  385.  
  386.         if (mBluetoothAdapter.getScanMode() !=
  387.  
  388.                 BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
  389.  
  390.             Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  391.  
  392.             discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
  393.  
  394.             startActivity(discoverableIntent);
  395.  
  396.         }
  397.  
  398.     }
  399.  
  400.  
  401.     /**
  402.      * Sends a message.
  403.      *
  404.      * @param message A string of text to send.
  405.      */
  406.  
  407.     private void sendMessage(String message) {
  408.  
  409.         // Check that we're actually connected before trying anything
  410.  
  411.         if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
  412.  
  413.             Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
  414.  
  415.             return;
  416.  
  417.         }
  418.  
  419.  
  420.         // Check that there's actually something to send
  421.  
  422.         if (message.length() > 0) {
  423.  
  424.             // Get the message bytes and tell the BluetoothChatService to write
  425.  
  426.             byte[] send = message.getBytes();
  427.  
  428.             mChatService.write(send);
  429.  
  430.  
  431.             // Reset out string buffer to zero and clear the edit text field
  432.  
  433.             mOutStringBuffer.setLength(0);
  434.  
  435.             mOutEditText.setText(mOutStringBuffer);
  436.  
  437.         }
  438.  
  439.     }
  440.  
  441.  
  442.     /**
  443.      * The action listener for the EditText widget, to listen for the return key
  444.      */
  445.  
  446.     private TextView.OnEditorActionListener mWriteListener
  447.  
  448.             = new TextView.OnEditorActionListener() {
  449.  
  450.         public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
  451.  
  452.             // If the action is a key-up event on the return key, send the message
  453.  
  454.             if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
  455.  
  456.                 String message = view.getText().toString();
  457.  
  458.                 sendMessage(message);
  459.  
  460.             }
  461.  
  462.             return true;
  463.  
  464.         }
  465.  
  466.     };
  467.  
  468.  
  469.     /**
  470.      * Updates the status on the action bar.
  471.      *
  472.      * @param resId a string resource ID
  473.      */
  474.  
  475.     private void setStatus(int resId) {
  476.  
  477.         FragmentActivity activity = getActivity();
  478.  
  479.         if (null == activity) {
  480.  
  481.             return;
  482.  
  483.         }
  484.  
  485.         final ActionBar actionBar = activity.getActionBar();
  486.  
  487.         if (null == actionBar) {
  488.  
  489.             return;
  490.  
  491.         }
  492.  
  493.         actionBar.setSubtitle(resId);
  494.  
  495.     }
  496.  
  497.  
  498.     /**
  499.      * Updates the status on the action bar.
  500.      *
  501.      * @param subTitle status
  502.      */
  503.  
  504.     private void setStatus(CharSequence subTitle) {
  505.  
  506.         FragmentActivity activity = getActivity();
  507.  
  508.         if (null == activity) {
  509.  
  510.             return;
  511.  
  512.         }
  513.  
  514.         final ActionBar actionBar = activity.getActionBar();
  515.  
  516.         if (null == actionBar) {
  517.  
  518.             return;
  519.  
  520.         }
  521.  
  522.         actionBar.setSubtitle(subTitle);
  523.  
  524.     }
  525.  
  526.  
  527.     /**
  528.      * The Handler that gets information back from the BluetoothChatService
  529.      */
  530.  
  531.     private final Handler mHandler = new Handler() {
  532.  
  533.         @Override
  534.  
  535.         public void handleMessage(Message msg) {
  536.  
  537.             FragmentActivity activity = getActivity();
  538.  
  539.             switch (msg.what) {
  540.  
  541.                 case Constants.MESSAGE_STATE_CHANGE:
  542.  
  543.                     switch (msg.arg1) {
  544.  
  545.                         case BluetoothChatService.STATE_CONNECTED:
  546.  
  547.                             setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
  548.  
  549.                             mConversationArrayAdapter.clear();
  550.  
  551.                             break;
  552.  
  553.                         case BluetoothChatService.STATE_CONNECTING:
  554.  
  555.                             setStatus(R.string.title_connecting);
  556.  
  557.                             break;
  558.  
  559.                         case BluetoothChatService.STATE_LISTEN:
  560.  
  561.                         case BluetoothChatService.STATE_NONE:
  562.  
  563.                             setStatus(R.string.title_not_connected);
  564.  
  565.                             break;
  566.  
  567.                     }
  568.  
  569.                     break;
  570.  
  571.                 case Constants.MESSAGE_WRITE:
  572.  
  573.                     byte[] writeBuf = (byte[]) msg.obj;
  574.  
  575.                     // construct a string from the buffer
  576.  
  577.                     String writeMessage = new String(writeBuf);
  578.                     //String writeMessage="aaa";
  579.  
  580.                     mConversationArrayAdapter.add(writeMessage);
  581.  
  582.                     break;
  583.  
  584.                 case Constants.MESSAGE_READ:
  585.  
  586.                     byte[] readBuf = (byte[]) msg.obj;
  587.  
  588.                     // construct a string from the valid bytes in the buffer
  589.  
  590.                     // String readMessage = new String(readBuf, 0, msg.arg1);
  591.  
  592.                     String readMessage = new String(readBuf, 0, 80);
  593.  
  594.                     //Operator ID, inteiro de 0 a 9
  595.                     Mensagem ID = new Mensagem();
  596.                     ID.setMensagem(readMessage.substring(1, 3));
  597.                     String palavra = ID.getMessagem();
  598.  
  599.                     //Message counter, inteiro de 0 a 65535
  600.                     Mensagem MessageCounter = new Mensagem();
  601.                     MessageCounter.setMensagem(readMessage.substring(3, 7));
  602.  
  603.                     //Step Counter, inteiro de 0 a 65535
  604.                     Mensagem StepCounter = new Mensagem();
  605.                     StepCounter.setMensagem(readMessage.substring(7, 11));
  606.  
  607.                     //Flag x 16: bit0: initial stance OK, bit1: no magnetic calibration, bit2: operator KO,
  608.                     // bit3: high temperature
  609.                     Mensagem Flag = new Mensagem();
  610.                     Flag.setMensagem(readMessage.substring(11, 15));
  611.  
  612.                     // Position estimation given by integration of inertial and magnetic data, X (North), LSB 0.1 m,
  613.                     // value from -52.4288 km to +52.4288 km
  614.                     Mensagem PositionIMX = new Mensagem();
  615.                     PositionIMX.setMensagem(readMessage.substring(15, 20));
  616.  
  617.                     // Position estimation given by integration of inertial and magnetic data, Y (East) , LSB 0.1 m,
  618.                     // value from -52.4288 km to +52.4288 km
  619.                     Mensagem PositionIMY = new Mensagem();
  620.                     PositionIMY.setMensagem(readMessage.substring(20, 25));
  621.  
  622.                     //Position estimation given by integration of inertial data only, X (North) , LSB 0.1 m,
  623.                     // value from -52.4288 km to +52.4288 km 8
  624.                     Mensagem PositionIX = new Mensagem();
  625.                     PositionIX.setMensagem(readMessage.substring(25, 30));
  626.  
  627.                     // Position estimation given by integration of inertial data only, Y (East) , LSB 0.1 m,
  628.                     // value from -52.4288 km to +52.4288 km
  629.                     Mensagem PositionIY = new Mensagem();
  630.                     PositionIY.setMensagem(readMessage.substring(30, 35));
  631.  
  632.                     //Altitude estimation given by integration of inertial data only, Z (Down) , LSB 0.1 m,
  633.                     // value from -3276.8 m to +3276.8 m
  634.                     Mensagem PositionIZ = new Mensagem();
  635.                     PositionIZ.setMensagem(readMessage.substring(35, 39));
  636.  
  637.                     //Altitude estimation given by pressometer, Z (Down), LSB 0.1 m, value from -3276.8 m to +3276.8 m
  638.                     Mensagem Altitude = new Mensagem();
  639.                     Altitude.setMensagem(readMessage.substring(39, 43));
  640.  
  641.                     // Latitude estimation from GPS, LSB = 2^-29 rad (nearly 1.2 c at sea level),
  642.                     // value from –PI/2 to +PI/2 rad
  643.                     Mensagem Latitude = new Mensagem();
  644.                     Latitude.setMensagem(readMessage.substring(43, 51));
  645.  
  646.                     // Longitude estimation from GPS, LSB = 2^-29 rad (nearly 1.2 c at sea level),
  647.                     // value from –PI to +PI rad
  648.                     Mensagem Longitude = new Mensagem();
  649.                     Longitude.setMensagem(readMessage.substring(51, 59));
  650.  
  651.                     //GPS estimation quality, value from 0 to 99
  652.                     Mensagem GPS = new Mensagem();
  653.                     GPS.setMensagem(readMessage.substring(59, 61));
  654.  
  655.                     //North alignment angle of inertial path, LSB 2^-13 rad, value from –PI to PI rad
  656.                     Mensagem Angle = new Mensagem();
  657.                     Angle.setMensagem(readMessage.substring(61, 65));
  658.  
  659.                     //Yaw drift of inertial path, in rotation per step, LSB 2^-19 rad,
  660.                     // value from –3.56 to 3.56 rad
  661.                     Mensagem Drift = new Mensagem();
  662.                     Drift.setMensagem(readMessage.substring(65, 69));
  663.  
  664.                     //CRC-CCITT
  665.                     Mensagem CRC = new Mensagem();
  666.                     CRC.setMensagem(readMessage.substring(69, 73));
  667.                     //String hex="FE" ;
  668.  
  669.  
  670.  
  671.                     if(i<=3) {
  672.                         hexX="00000";
  673.                         hexY="00000";
  674.                         i++;
  675.                     }
  676.                     else {
  677.                         hexX=PositionIMX.getMessagem();
  678.                         hexY=PositionIMX.getMessagem();
  679.                     }
  680.                     decimalX=Integer.parseInt(hexX,16);
  681.                     decimalY=Integer.parseInt(hexY,16);
  682.  
  683.                     //String valor= Integer.toString(decimal);
  684.                     // mConversationArrayAdapter.add(mConnectedDeviceName + ":  " + readMessage);
  685.                     // mConversationArrayAdapter.add("XXXXXX "+readMessage+"XXXXXX");
  686. //                    mConversationArrayAdapter.add("XXXXXX "+readMessage+"XXXXXX"+ID.getMessagem()
  687. //                            +MessageCounter.getMessagem()+StepCounter.getMessagem()+Flag.getMessagem());
  688.  
  689.                     //mConversationArrayAdapter.add("X:"+PositionIMX.getMessagem()+" Y:"
  690.                     //      +PositionIMY.getMessagem()+"XX" +decimal);
  691.                     //System.out.println(decimal);
  692.  
  693.                     mConversationArrayAdapter.add("X:"+decimalX+" Y:"+decimalY);
  694.  
  695.                     break;
  696.  
  697.                 case Constants.MESSAGE_DEVICE_NAME:
  698.  
  699.                     // save the connected device's name
  700.  
  701.                     mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
  702.  
  703.                     if (null != activity) {
  704.  
  705.                         Toast.makeText(activity, "Connected to "
  706.  
  707.                                 + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
  708.  
  709.                     }
  710.  
  711.                     break;
  712.  
  713.                 case Constants.MESSAGE_TOAST:
  714.  
  715.                     if (null != activity) {
  716.  
  717.                         Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
  718.  
  719.                                 Toast.LENGTH_SHORT).show();
  720.  
  721.                     }
  722.  
  723.                     break;
  724.  
  725.             }
  726.  
  727.         }
  728.  
  729.     };
  730.  
  731.  
  732.     public void onActivityResult(int requestCode, int resultCode, Intent data) {
  733.  
  734.         switch (requestCode) {
  735.  
  736.             case REQUEST_CONNECT_DEVICE_SECURE:
  737.  
  738.                 // When DeviceListActivity returns with a device to connect
  739.  
  740.                 if (resultCode == Activity.RESULT_OK) {
  741.  
  742.                     connectDevice(data, true);
  743.  
  744.                 }
  745.  
  746.                 break;
  747.  
  748.             case REQUEST_CONNECT_DEVICE_INSECURE:
  749.  
  750.                 // When DeviceListActivity returns with a device to connect
  751.  
  752.                 if (resultCode == Activity.RESULT_OK) {
  753.  
  754.                     connectDevice(data, false);
  755.  
  756.                 }
  757.  
  758.                 break;
  759.  
  760.             case REQUEST_ENABLE_BT:
  761.  
  762.                 // When the request to enable Bluetooth returns
  763.  
  764.                 if (resultCode == Activity.RESULT_OK) {
  765.  
  766.                     // Bluetooth is now enabled, so set up a chat session
  767.  
  768.                     setupChat();
  769.  
  770.                 } else {
  771.  
  772.                     // User did not enable Bluetooth or an error occurred
  773.  
  774.                     Log.d(TAG, "BT not enabled");
  775.  
  776.                     FragmentActivity activity = getActivity();
  777.  
  778.                     if (activity != null) {
  779.  
  780.                         Toast.makeText(activity, R.string.bt_not_enabled_leaving,
  781.  
  782.                                 Toast.LENGTH_SHORT).show();
  783.  
  784.                         activity.finish();
  785.  
  786.                     }
  787.  
  788.                 }
  789.  
  790.         }
  791.  
  792.     }
  793.  
  794.  
  795.     /**
  796.      * Establish connection with other device
  797.      *
  798.      * @param data   An {@link Intent} with {@link DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
  799.      * @param secure Socket Security type - Secure (true) , Insecure (false)
  800.      */
  801.  
  802.     private void connectDevice(Intent data, boolean secure) {
  803.  
  804.         // Get the device MAC address
  805.  
  806.         Bundle extras = data.getExtras();
  807.  
  808.         if (extras == null) {
  809.  
  810.             return;
  811.  
  812.         }
  813.  
  814.         String address = extras.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
  815.  
  816.         // Get the BluetoothDevice object
  817.  
  818.         BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  819.  
  820.         // Attempt to connect to the device
  821.  
  822.         mChatService.connect(device, secure);
  823.  
  824.     }
  825.  
  826.  
  827.     @Override
  828.  
  829.     public void onCreateOptionsMenu(@NonNull Menu menu, MenuInflater inflater) {
  830.  
  831.  
  832.         inflater.inflate(R.menu.bluetooth_chat, menu);
  833.  
  834.     }
  835.  
  836.  
  837.     @Override
  838.  
  839.     public boolean onOptionsItemSelected(MenuItem item) {
  840.  
  841.         switch (item.getItemId()) {
  842.  
  843.             case R.id.secure_connect_scan: {
  844.  
  845.                 // Launch the DeviceListActivity to see devices and do scan
  846.  
  847.                 Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
  848.  
  849.                 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
  850.  
  851.                 return true;
  852.  
  853.             }
  854.  
  855.             case R.id.insecure_connect_scan: {
  856.  
  857.                 // Launch the DeviceListActivity to see devices and do scan
  858.  
  859.                 Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
  860.  
  861.                 startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
  862.  
  863.                 return true;
  864.  
  865.             }
  866.  
  867.             case R.id.discoverable: {
  868.  
  869.                 // Ensure this device is discoverable by others
  870.  
  871.                 ensureDiscoverable();
  872.  
  873.                 return true;
  874.  
  875.             }
  876.  
  877.         }
  878.  
  879.         return false;
  880.  
  881.     }
  882.  
  883.     public class Mensagem {
  884.         private String mensagem;
  885.  
  886.         // Getter
  887.         public String getMessagem() {
  888.  
  889.             return mensagem;
  890.         }
  891.  
  892.         //Setter
  893.         public void setMensagem(String m) {
  894.  
  895.             this.mensagem = m;
  896.  
  897.  
  898.         }
  899.  
  900.  
  901.  
  902.     }
  903.  
  904.     public static class Decimal{
  905.         int ValorX = decimalX;
  906.         int ValorY = decimalY;
  907.  
  908.     }
  909.  
  910.  
  911. }
  912.  
  913.  
  914.  
  915.  
  916. /*
  917.  * Copyright (C) 2014 The Android Open Source Project
  918.  *
  919.  * Licensed under the Apache License, Version 2.0 (the "License");
  920.  * you may not use this file except in compliance with the License.
  921.  * You may obtain a copy of the License at
  922.  *
  923.  *      http://www.apache.org/licenses/LICENSE-2.0
  924.  *
  925.  * Unless required by applicable law or agreed to in writing, software
  926.  * distributed under the License is distributed on an "AS IS" BASIS,
  927.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  928.  * See the License for the specific language governing permissions and
  929.  * limitations under the License.
  930.  */
  931.  
  932. package com.example.android.bluetoothchat;
  933.  
  934. import android.app.Activity;
  935. import android.bluetooth.BluetoothAdapter;
  936. import android.bluetooth.BluetoothDevice;
  937. import android.content.BroadcastReceiver;
  938. import android.content.Context;
  939. import android.content.Intent;
  940. import android.content.IntentFilter;
  941. import android.graphics.Color;
  942. import android.icu.text.Transliterator;
  943. import android.os.Bundle;
  944. import android.os.Handler;
  945. import android.view.View;
  946. import android.view.Window;
  947. import android.widget.AdapterView;
  948. import android.widget.ArrayAdapter;
  949. import android.widget.Button;
  950. import android.widget.ListView;
  951. import android.widget.TextView;
  952.  
  953. import com.example.android.common.logger.Log;
  954. import com.jjoe64.graphview.GraphView;
  955. import com.jjoe64.graphview.GridLabelRenderer;
  956. import com.jjoe64.graphview.series.DataPoint;
  957. import com.jjoe64.graphview.series.LineGraphSeries;
  958.  
  959. import java.util.Random;
  960. import java.util.Set;
  961.  
  962.  
  963. /**
  964.  * This Activity appears as a dialog. It lists any paired devices and
  965.  * devices detected in the area after discovery. When a device is chosen
  966.  * by the user, the MAC address of the device is sent back to the parent
  967.  * Activity in the result Intent.
  968.  */
  969. public class DeviceListActivity extends Activity {
  970.  
  971.  
  972.     public int i =0;
  973.  
  974.  
  975.     //#graphView
  976.  
  977.     private final Handler mHandler = new Handler();
  978.     private Runnable mTimer;
  979.     private double graphLastXValue = 5d;
  980.     private double yvalue = 5d;
  981.     private LineGraphSeries<DataPoint> mSeries;
  982.  
  983.  
  984.     /**
  985.      * Tag for Log
  986.      */
  987.     private static final String TAG = "DeviceListActivity";
  988.  
  989.     /**
  990.      * Return Intent extra
  991.      */
  992.     public static String EXTRA_DEVICE_ADDRESS = "device_address";
  993.  
  994.     /**
  995.      * Member fields
  996.      */
  997.     private BluetoothAdapter mBtAdapter;
  998.  
  999.     /**
  1000.      * Newly discovered devices
  1001.      */
  1002.     private ArrayAdapter<String> mNewDevicesArrayAdapter;
  1003.  
  1004.  
  1005.  
  1006.     @Override
  1007.     protected void onCreate(Bundle savedInstanceState) {
  1008.         super.onCreate(savedInstanceState);
  1009.  
  1010.  
  1011.         if(i<=3) {
  1012.             i++;
  1013.         }
  1014.         else {
  1015.             GraphView graph = (GraphView) findViewById(R.id.graph);
  1016.             initGraph(graph);
  1017.         }
  1018.  
  1019.  
  1020.  
  1021.         // Setup the window
  1022.         requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
  1023.         setContentView(R.layout.activity_device_list);
  1024.  
  1025.         // Set result CANCELED in case the user backs out
  1026.         setResult(Activity.RESULT_CANCELED);
  1027.  
  1028.         // Initialize the button to perform device discovery
  1029.         Button scanButton = findViewById(R.id.button_scan);
  1030.         scanButton.setOnClickListener(new View.OnClickListener() {
  1031.             public void onClick(View v) {
  1032.                 doDiscovery();
  1033.                 v.setVisibility(View.GONE);
  1034.             }
  1035.         });
  1036.  
  1037.         // Initialize array adapters. One for already paired devices and
  1038.         // one for newly discovered devices
  1039.         ArrayAdapter<String> pairedDevicesArrayAdapter =
  1040.                 new ArrayAdapter<>(this, R.layout.device_name);
  1041.         mNewDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
  1042.  
  1043.         // Find and set up the ListView for paired devices
  1044.         ListView pairedListView = findViewById(R.id.paired_devices);
  1045.         pairedListView.setAdapter(pairedDevicesArrayAdapter);
  1046.         pairedListView.setOnItemClickListener(mDeviceClickListener);
  1047.  
  1048.         // Find and set up the ListView for newly discovered devices
  1049.         ListView newDevicesListView = findViewById(R.id.new_devices);
  1050.         newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
  1051.         newDevicesListView.setOnItemClickListener(mDeviceClickListener);
  1052.  
  1053.         // Register for broadcasts when a device is discovered
  1054.         IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  1055.         this.registerReceiver(mReceiver, filter);
  1056.  
  1057.         // Register for broadcasts when discovery has finished
  1058.         filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  1059.         this.registerReceiver(mReceiver, filter);
  1060.  
  1061.         // Get the local Bluetooth adapter
  1062.         mBtAdapter = BluetoothAdapter.getDefaultAdapter();
  1063.  
  1064.         // Get a set of currently paired devices
  1065.         Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
  1066.  
  1067.         // If there are paired devices, add each one to the ArrayAdapter
  1068.         if (pairedDevices.size() > 0) {
  1069.             findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
  1070.             for (BluetoothDevice device : pairedDevices) {
  1071.                 pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
  1072.             }
  1073.         } else {
  1074.             String noDevices = getResources().getText(R.string.none_paired).toString();
  1075.             pairedDevicesArrayAdapter.add(noDevices);
  1076.         }
  1077.  
  1078.  
  1079.     }
  1080.  
  1081.  
  1082.     public void initGraph(GraphView graph)
  1083.     {
  1084.         graph.getViewport().setXAxisBoundsManual(true);
  1085.  
  1086.  
  1087.  
  1088.         graph.getViewport().setMinX(0);
  1089.  
  1090.         graph.getViewport().setMaxX(1048575);
  1091.  
  1092.  
  1093.  
  1094.         graph.getViewport().setYAxisBoundsManual(true);
  1095.  
  1096.         graph.getViewport().setMinY(0);
  1097.  
  1098.         graph.getViewport().setMaxY(1048575);
  1099.  
  1100.  
  1101.  
  1102.         graph.getViewport().setScrollable(true); // enables horizontal scrolling
  1103.  
  1104.         graph.getViewport().setScalable(true); // enables horizontal zooming and scrolling
  1105.  
  1106.  
  1107.  
  1108.  
  1109.  
  1110.         //graph.getGridLabelRenderer().setLabelVerticalWidth(100);
  1111.  
  1112.         GridLabelRenderer gridLabel = graph.getGridLabelRenderer();
  1113.  
  1114.         gridLabel.setHorizontalAxisTitle("x axis");
  1115.  
  1116.         gridLabel.setVerticalAxisTitle("y axis");
  1117.  
  1118.  
  1119.  
  1120.         // first mSeries is a line
  1121.  
  1122.         mSeries = new LineGraphSeries<>();
  1123.  
  1124.         mSeries.setDrawDataPoints(false);
  1125.  
  1126.         mSeries.setDrawBackground(true);
  1127.  
  1128.         graph.addSeries(mSeries);
  1129.  
  1130.         mSeries.setColor(Color.RED);
  1131.     }
  1132.  
  1133.  
  1134.     //#graphView
  1135.    // double mLastRandom = 2;
  1136.     // String sharedFact = mDataField.getText().toString();
  1137.     //double yvalue = Double.parseDouble(data);
  1138.     //Random mRand = new Random();
  1139.    // private double getRandom()
  1140.     //{
  1141.   //      mLastRandom += mRand.nextDouble()*0.05 - 0.05;
  1142.   //      return mLastRandom ;
  1143.   //  }
  1144.  
  1145.  
  1146.  
  1147.     @Override
  1148.  
  1149.     public void onResume() {
  1150.  
  1151.         super.onResume();
  1152.  
  1153.         //#graphView
  1154.         mTimer = new Runnable()
  1155.         {
  1156.             @Override
  1157.             public void run()
  1158.             {
  1159.                 graphLastXValue += 1.0;
  1160.  
  1161.               BluetoothChatFragment.Decimal Xvalue= new BluetoothChatFragment.Decimal();
  1162.               BluetoothChatFragment.Decimal Yvalue= new BluetoothChatFragment.Decimal();
  1163.  
  1164.  
  1165.  
  1166.                 double a =Xvalue.ValorX;
  1167.                 double b =Yvalue.ValorY;
  1168.                 mSeries.appendData(new DataPoint(graphLastXValue, graphLastXValue),
  1169.                        true, 22);
  1170.  
  1171.                //mSeries.appendData(new DataPoint(Xvalue.ValorX,Yvalue.ValorY),
  1172.                 //       true, 100);
  1173.  
  1174.                // mHandler.postDelayed(this, 330);
  1175.             }
  1176.         };
  1177.         mHandler.postDelayed(mTimer, 1500);
  1178.  
  1179.  
  1180.  
  1181.     }
  1182.  
  1183.  
  1184.     @Override
  1185.     protected void onDestroy() {
  1186.         super.onDestroy();
  1187.  
  1188.         // Make sure we're not doing discovery anymore
  1189.         if (mBtAdapter != null) {
  1190.             mBtAdapter.cancelDiscovery();
  1191.         }
  1192.  
  1193.         // Unregister broadcast listeners
  1194.         this.unregisterReceiver(mReceiver);
  1195.     }
  1196.  
  1197.     /**
  1198.      * Start device discover with the BluetoothAdapter
  1199.      */
  1200.     private void doDiscovery() {
  1201.         Log.d(TAG, "doDiscovery()");
  1202.  
  1203.         // Indicate scanning in the title
  1204.         setProgressBarIndeterminateVisibility(true);
  1205.         setTitle(R.string.scanning);
  1206.  
  1207.         // Turn on sub-title for new devices
  1208.         findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
  1209.  
  1210.         // If we're already discovering, stop it
  1211.         if (mBtAdapter.isDiscovering()) {
  1212.             mBtAdapter.cancelDiscovery();
  1213.         }
  1214.  
  1215.         // Request discover from BluetoothAdapter
  1216.         mBtAdapter.startDiscovery();
  1217.     }
  1218.  
  1219.     /**
  1220.      * The on-click listener for all devices in the ListViews
  1221.      */
  1222.     private AdapterView.OnItemClickListener mDeviceClickListener
  1223.             = new AdapterView.OnItemClickListener() {
  1224.         public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
  1225.             // Cancel discovery because it's costly and we're about to connect
  1226.             mBtAdapter.cancelDiscovery();
  1227.  
  1228.             // Get the device MAC address, which is the last 17 chars in the View
  1229.             String info = ((TextView) v).getText().toString();
  1230.             String address = info.substring(info.length() - 17);
  1231.  
  1232.             // Create the result Intent and include the MAC address
  1233.             Intent intent = new Intent();
  1234.             intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
  1235.  
  1236.             // Set result and finish this Activity
  1237.             setResult(Activity.RESULT_OK, intent);
  1238.             finish();
  1239.         }
  1240.     };
  1241.  
  1242.     /**
  1243.      * The BroadcastReceiver that listens for discovered devices and changes the title when
  1244.      * discovery is finished
  1245.      */
  1246.     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  1247.         @Override
  1248.         public void onReceive(Context context, Intent intent) {
  1249.             String action = intent.getAction();
  1250.  
  1251.             // When discovery finds a device
  1252.             if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  1253.                 // Get the BluetoothDevice object from the Intent
  1254.                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  1255.                 // If it's already paired, skip it, because it's been listed already
  1256.                 if (device != null && device.getBondState() != BluetoothDevice.BOND_BONDED) {
  1257.                     mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
  1258.                 }
  1259.                 // When discovery is finished, change the Activity title
  1260.             } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
  1261.                 setProgressBarIndeterminateVisibility(false);
  1262.                 setTitle(R.string.select_device);
  1263.                 if (mNewDevicesArrayAdapter.getCount() == 0) {
  1264.                     String noDevices = getResources().getText(R.string.none_found).toString();
  1265.                     mNewDevicesArrayAdapter.add(noDevices);
  1266.                 }
  1267.             }
  1268.         }
  1269.     };
  1270.  
  1271. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement