Created
August 3, 2019 07:52
-
-
Save elktros/3a18fb42ca86982a553f11cb2cecc278 to your computer and use it in GitHub Desktop.
Quadruped_Robot_Main2chatActivity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.ProgressDialog; | |
import android.bluetooth.BluetoothAdapter; | |
import android.bluetooth.BluetoothDevice; | |
import android.bluetooth.BluetoothSocket; | |
import android.content.Intent; | |
import android.os.AsyncTask; | |
import android.os.Handler; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.util.Log; | |
import android.view.View; | |
import android.widget.EditText; | |
import android.widget.ListView; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.util.UUID; | |
import ai.api.AIServiceContext; | |
import ai.api.AIServiceContextBuilder; | |
import ai.api.android.AIConfiguration; | |
import ai.api.android.AIDataService; | |
import ai.api.model.AIRequest; | |
import ai.api.model.AIResponse; | |
public class Main2chatActivity extends AppCompatActivity { | |
private EditText editText; | |
private MessageAdapter messageAdapter; | |
private static final String TAG = Main2chatActivity.class.getSimpleName(); | |
private ProgressDialog progress; | |
private ListView messagesView; | |
private AIRequest aiRequest; | |
private AIDataService aiDataService; | |
private AIServiceContext customAIServiceContext; | |
OutputStream mmOutputStream; | |
InputStream mmInputStream; | |
private String uuid = UUID.randomUUID().toString(); | |
String address = null; | |
BluetoothAdapter myBluetooth = null; | |
BluetoothDevice mmDevice; | |
BluetoothSocket btSocket = null; | |
BluetoothSocket mmSocket = null; | |
private boolean isBtConnected = false; | |
int readBufferPosition; | |
int counter; | |
Thread workerThread; | |
byte[] readBuffer; | |
volatile boolean stopWorker; | |
//SPP UUID Look for it | |
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main2chat); | |
editText = (EditText) findViewById(R.id.editText); | |
Intent newint = getIntent(); | |
address = newint.getStringExtra(bluetoothActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device | |
new ConnectBT().execute(); | |
messageAdapter = new MessageAdapter(this); | |
messagesView = (ListView) findViewById(R.id.messages_view); | |
messagesView.setAdapter(messageAdapter); | |
} | |
public void sendMessage(View view) { | |
String message = editText.getText().toString(); | |
if (message.length() > 0) { | |
final Message message1 = new Message(message,true); | |
messageAdapter.add(message1); | |
editText.getText().clear(); | |
//Dialogflow configuration | |
// Unique key is obtained from dialogflow settings | |
final AIConfiguration config = new AIConfiguration("<<key>>", | |
AIConfiguration.SupportedLanguages.English, | |
AIConfiguration.RecognitionEngine.System); | |
aiDataService = new AIDataService(this, config); | |
customAIServiceContext = AIServiceContextBuilder.buildFromSessionId(uuid);// helps to create new session whenever app restarts | |
aiRequest = new AIRequest(); | |
aiRequest.setQuery(message); | |
// Dialogflow request | |
RequestTask requestTask = new RequestTask(Main2chatActivity.this, aiDataService, customAIServiceContext); | |
requestTask.execute(aiRequest);// background task | |
} | |
} | |
// Dialogflow response | |
public void callback(AIResponse aiResponse) { | |
if (aiResponse != null) { | |
// process aiResponse here | |
String botReply = aiResponse.getResult().getFulfillment().getSpeech(); | |
Log.d(TAG, "Bot Reply: " + botReply.contains("Hello!")); | |
char first='z'; | |
//response: Hello | |
if(botReply.contains("Hello!"))// wave hello | |
{ | |
first='h'; | |
} | |
//response: Hm. I will check and tell you | |
else if(botReply.contains("check")) //navigation check | |
{ | |
first='c'; | |
} | |
//response: haha. No, it is not possible. | |
else if(botReply.contains("possible")) //fly | |
{ | |
first='p'; | |
} | |
if (btSocket!=null && first!='z') | |
{ | |
try | |
{ | |
btSocket.getOutputStream().write(String.valueOf(first).getBytes()); | |
if(first=='c') | |
openBT();// receive message from arduino | |
} | |
catch (IOException e) | |
{ | |
Log.d("","Error"); | |
} | |
} | |
final Message message1 = new Message(botReply,false); | |
messageAdapter.add(message1); | |
} else { | |
Log.d(TAG, "Bot Reply: Null"); | |
} | |
} | |
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread | |
{ | |
private boolean ConnectSuccess = true; | |
@Override | |
protected void onPreExecute() | |
{ | |
progress = ProgressDialog.show(Main2chatActivity.this, "Connecting...", "Please wait!!!"); //show a progress dialog | |
} | |
@Override | |
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background | |
{ | |
try | |
{ | |
if (btSocket == null || !isBtConnected) | |
{ | |
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device | |
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available | |
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection | |
BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); | |
btSocket.connect();//start connection | |
} | |
} | |
catch (IOException e) | |
{ | |
ConnectSuccess = false;//if the try failed, you can check the exception here | |
} | |
return null; | |
} | |
@Override | |
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine | |
{ | |
super.onPostExecute(result); | |
if (!ConnectSuccess) | |
{ | |
Log.d("error","Connection Failed. Is it a SPP Bluetooth? Try again"); | |
finish(); | |
} | |
else | |
{ | |
Log.d("Success","Connected."); | |
isBtConnected = true; | |
} | |
progress.dismiss(); | |
} | |
} | |
//function to listen data | |
void openBT() throws IOException | |
{ | |
/* UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID | |
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); | |
mmSocket.connect();*/ | |
mmOutputStream = btSocket.getOutputStream(); | |
mmInputStream = btSocket.getInputStream(); | |
beginListenForData(); | |
} | |
//function to read input from arduino | |
void beginListenForData() | |
{ | |
final Handler handler = new Handler(); | |
final byte delimiter = 10; //This is the ASCII code for a newline character | |
stopWorker = false; | |
readBufferPosition = 0; | |
readBuffer = new byte[1024]; | |
workerThread = new Thread(new Runnable() | |
{ | |
public void run() | |
{ | |
while(!Thread.currentThread().isInterrupted() && !stopWorker) | |
{ | |
try | |
{ | |
int bytesAvailable = mmInputStream.available(); | |
if(bytesAvailable > 0) | |
{ | |
byte[] packetBytes = new byte[bytesAvailable]; | |
mmInputStream.read(packetBytes); | |
for(int i=0;i<bytesAvailable;i++) | |
{ | |
byte b = packetBytes[i]; | |
if(b == delimiter) | |
{ | |
byte[] encodedBytes = new byte[readBufferPosition]; | |
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length); | |
final String data = new String(encodedBytes, "US-ASCII"); | |
readBufferPosition = 0; | |
handler.post(new Runnable() | |
{ | |
public void run() | |
{ | |
final Message message1 = new Message("Some object is there at a distance of "+data.toString()+" cms from my point. So i can't move\uD83D\uDE1F",false); | |
messageAdapter.add(message1); | |
Log.d("Value",data); | |
} | |
}); | |
} | |
else | |
{ | |
readBuffer[readBufferPosition++] = b; | |
} | |
} | |
} | |
} | |
catch (IOException ex) | |
{ | |
stopWorker = true; | |
} | |
} | |
} | |
}); | |
workerThread.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment