Data packet reception via bluetooth at android GUI - android

I am pretty new to both arduino as well as the android domains. I am using arduino to send data to android using bluetooth module(linvor JY-MCU v.1.05). It is communicating with my app perfectly but i am not able to receive any data for this particular app. I am transferring a packet from arduino => ( $ 43 56 ! ) I want to extract it and display numbers alone on the android app.
Here $-header, 43-hr value, 56-temp value, !-footer
My arduino code is as follows:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
String command = ""; // Stores response of bluetooth device
// which simply allows \n between each
// response.
void setup() {
mySerial.begin(9600); // initialization
delay(25);
}
void loop()
{
mySerial.println("$-43:56^!"); // print message
delay(5000);
}
The string is like a packet. I want 43 to be displayed in an editbox and 56 to be displayed in a text box.
My android code is a vast one that checks bluetooth connectivity too. So i am limiting it to just a section. Could someone please help me out with the coding part of it to just display the two sets of numbers in two txtView1 and txtView2 respectively....
package com.example.projtrial;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import com.example.projtrial.R;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.view.Menu;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import java.util.regex.Pattern;
import java.util.Arrays;
import java.util.StringTokenizer;
public class MainActivity extends Activity {
private static final String TAG = "projtrial";
public EditView editView1;
public TextView textView1;
Handler h;
final int RECEIVE_MESSAGE = 1; //Handler status
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
//SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000- 00805F9B34FB");
// MAC-address of Bluetooth module
private static String address = "20:13:05:13:01:98";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText) findViewById(R.id.editText1);
textView1 = (TextView) findViewById(R.id.textView1);
h = new Handler() {
private String strIncom;
private String header;
private String hr;
private String tempr;
private String footer;
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECEIVE_MESSAGE: // If one receives a message
byte[] readBuf = (byte[]) msg.obj;
String header = new String(readBuf, 0, msg.arg1);
String[] separated = message.split("\\:");
editText1.setText("hr: " + separated[0]); //works
textView1.setText("temp:" + separated[1]); //doesnt work
}
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
/*try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}*/
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
}
}
}
}
Someone please help me out soon. I have been stuck up with dis for over a week. Thanking you in advance.
Sanj
"Case receive" and "Run" are the loops where the change has to be made.
Finding the index of a character "indexOf()" provides an error(string index out of bound).
I have tried switching off the bluetooth after entering the case receive block too but in vain.
Hoping to find a solution.

what does Message contains? with
byte[] readBuf = (byte[]) msg.obj;
String header = new String(readBuf, 0, msg.arg1);
all the consecutive
byte[] readBuf2 = (byte[]) msg.obj;
String hr = new String(readBuf2, 0, msg.arg1);
you are extrancing always the same data.
given the fact that in obj there are the chars between $ and ! included, then you can read all message
byte[] readBuf = (byte[]) msg.obj;
String message = new String(readBuf, 0, msg.arg1);
and then extract all the line
String[] cell = message.split("\n");
txtView1.setText("HR:" +cell[1]);
[...]
if in obj instead there are some byte[], then you have to add them to a buffer, then you remove all byte until $, add byte[] until you find a !, extract and remove from the buffer the data between the two delimeter, inclusive, and do what i said before. (well, this is just one solution)

Now right off the bat I haven't used bluetooth before but I'd say that the problem could be at these lines:
mySerial.println("$"); // print message
mySerial.println(23);
mySerial.println(546);
mySerial.println("!");
Because you are using println(); you send the message at each line as a separate packet hence the receiving end can't split it up and use the information.
I had a similar problem and fixed it by simply putting all the data needed in one string and the sending the whole string once.
The arduino coding language also for some reason cant join an integer and a string to another string just like that, It took me a while to figure it out but you simply have to use lines similar to this:
String output = "$";
output += 23; //or "23", not sure if it matters which one you use.
output += 546;
output += "!";
mySerial.println(output);

Related

Android Bluetooth connection with OBD port

I'm doing an application that comunicate with car by an OBD 2 port.
Now i'm working with bluetooth connection and i'm reading Android documentation and have some issues about connection and comunication with obd device.
I'm moving like this steps:
1)If bluetooth not active, activate the bluetooth
2)search device and show in a list
3)OnItemClick in the listview for connect with touched device (founded) with a client bluetooth connection
And here i have some problem to understand the Android documentation....
For the connection with device i use this code (like documentation)
foundedDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view,
final int position, long id) {
mBluetoothAdapter.cancelDiscovery();
String deviceName = (String)adapter.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "Selezionato: " + deviceName,
Toast.LENGTH_LONG).show();
for(BluetoothDevice dv : deviceList){
if(dv.getName() != null && dv.getName().equals(deviceName)){
selectedDevice = dv;
}
}
ConnectThread connectThread = new ConnectThread(selectedDevice);
connectThread.run();
}
});
//Thread of bluetooth connection
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket
// because mmSocket is final.
BluetoothSocket tmp = null;
mmDevice = device;
try {
// Get a BluetoothSocket to connect with the given BluetoothDevice.
// MY_UUID is the app's UUID string, also used in the server code.
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
Log.i(TAG, "Socket's create() successfull");
} catch (IOException e) {
Log.e(TAG, "Socket's create() method failed", e);
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
mBluetoothAdapter.cancelDiscovery();
Log.i(TAG, "run() eseguito");
try {
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and return.
try {
mmSocket.close();
} catch (IOException closeException) {
Log.e(TAG, "Could not close the client socket", closeException);
}
return;
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
//manageMyConnectedSocket(mmSocket);
}
// Closes the client socket and causes the thread to finish.
public void cancel() {
Log.i(TAG, "cancel() eseguito");
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the client socket", e);
}
}
}
I'm not sure about the connectThread.run() they don't explain the usage of method inside ConnectThread and i don't know how declare the manageMyConnectedSocket(mmSocket);
For the comunication i create a class MyBluetoothService.java and like documentation i write this code:
package com.tesi.ddz.obd_project;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by ddz on 24/04/17.
*/
public class MyBluetoothService{
private static final String TAG = "MY_APP_DEBUG_TAG";
private Handler mHandler; // handler that gets info from Bluetooth service
// Defines several constants used when transmitting messages between the
// service and the UI.
private interface MessageConstants {
public static final int MESSAGE_READ = 0;
public static final int MESSAGE_WRITE = 1;
public static final int MESSAGE_TOAST = 2;
// ... (Add other message types here as needed.)
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private byte[] mmBuffer; // mmBuffer store for the stream
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams; using temp objects because
// member streams are final.
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating input stream", e);
}
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "Error occurred when creating output stream", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
mmBuffer = new byte[1024];
int numBytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
try {
// Read from the InputStream.
numBytes = mmInStream.read(mmBuffer);
// Send the obtained bytes to the UI activity.
Message readMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_READ, numBytes, -1,
mmBuffer);
readMsg.sendToTarget();
} catch (IOException e) {
Log.d(TAG, "Input stream was disconnected", e);
break;
}
}
}
// Call this from the main activity to send data to the remote device.
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
// Share the sent message with the UI activity.
Message writtenMsg = mHandler.obtainMessage(
MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
writtenMsg.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Error occurred when sending data", e);
// Send a failure message back to the activity.
Message writeErrorMsg =
mHandler.obtainMessage(MessageConstants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString("toast",
"Couldn't send data to the other device");
writeErrorMsg.setData(bundle);
mHandler.sendMessage(writeErrorMsg);
}
}
// Call this method from the main activity to shut down the connection.
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close the connect socket", e);
}
}
}
}
I would implement the method manageMyConnectedSocket(mmSocket); by calling the class MyBluetoothService.java and manage the connection as i understand the documentation....
They declare ConnectedThread as private so i can't call this method in the MainActivity.java.... so what is the best way to implement this connection?
Don't use MyBluetoothService and declare all to the MainActivity or keep working like that and maybe declare ConnectedThred public so i can use it in the MainActivity?
Especially i don't understand how use the class MyBluetoothService.java and the method manageMyConnectionSocket(mmsocket)

How do I receive bluetooth data from arduino to android?

I use a temperature sensor connected to arduino, then send temperature information through bluetooth to my phone. My phone application has a complete UI and is ready to receive information.
Every single tutorial I see is used to do the bluetooth pairing. I have not done this part yet (because arduino code is not complete yet, so can't test), but assuming I use the phone options to do the pairing, I still have no idea how to do the data transmission.
How do I receive information on the phone and display it? Could anyone point me to a tutorial or an explanation/code on how to proceed?
Thanks in advance!
Look at this.... very effective. In this code, you take a MAC address by file and connect it to the device automatically. Then you can send and receive string data from Arduino. You can take inspiration from this code.
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Scroller;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
public class MainActivity extends Activity implements OnSeekBarChangeListener {
public String ultimodato;
////
private static final String TAG = "bluetooth2";
Handler h;
final int RECEIVE_MESSAGE = 1; //1 // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "00:14:02:13:00:10";
////
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
/* se non esiste il folder, creare il folder */
File folder = new File(Environment.getExternalStorageDirectory() + "/Asiagem");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
setContentView(R.layout.main);
//LETTURA DA FILE DEL MAC-ADDRESS A CUI CONNETTERSI
try{
String MACFile = readFileAsString("/sdcard/MAC.txt");
if(MACFile==""){
Toast.makeText(this,"Nessun dispositivo salvato, torno alla fase precedente", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
finish();
}else {
address = MACFile;
}
}catch(Exception e){
Toast.makeText(getApplicationContext(),"Errore nella lettura dei dati" , Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
finish();
}
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECEIVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
Toast.makeText(getBaseContext(), strIncom, Toast.LENGTH_SHORT).show();
Log.d("INCOME", "INCOME: " + strIncom);
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void SendMessageBT(View v){
//INVIO MESSAGGIO AL BLUETOOTH
mConnectedThread.write("U");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
previousTime = System.currentTimeMillis();
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
if(System.currentTimeMillis() - previousTime > 10000){
previousTime = System.currentTimeMillis();
mConnectedThread.write("w");
}
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
ultimodato=message;
to_send=true;
//connect();
new connect_and_send().execute();
}
}
}
private class connect_and_send extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() { // Fa vedere solo il dialog
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
btSocket.close();
Log.d(TAG, "...ALERT: " + "SOCKET CHIUSA" + "...");
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
Log.d(TAG, "...ALERT: " + "IMPOSSIBILE CHIUDERE SOCKET" + "...");
}
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//REINVIA L'ULTIMO DATO
if (to_send==true){
mConnectedThread.write(ultimodato);
to_send=false;
}
previousTime = System.currentTimeMillis();
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
public static String readFileAsString(String filePath) {
String result = "";
File file = new File(filePath);
if ( file.exists() ) {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
Log.d("TourGuide", e.toString());
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ignored) {
}
}
}
return result;
}
}

Send and receive string in both client and server sides using WiFi Direct

My application is a simple WiFi Direct chat. I can connect two devices, but I don't know how I should send and receive a String (not a File) in both sides (not just from client to server like the developer example)
In both sides: I just want an EditText and a Button that when clicked sends EditText.getText() to the other side
If anyone has full code, please send me a link. Thanks a lot
Android's WiFiDirectServiceDiscovery sample project does that:
package com.example.android.wifidirect.discovery;
import android.os.Handler;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* Handles reading and writing of messages with socket buffers. Uses a Handler
* to post messages to UI thread for UI updates.
*/
public class ChatManager implements Runnable {
private Socket socket = null;
private Handler handler;
public ChatManager(Socket socket, Handler handler) {
this.socket = socket;
this.handler = handler;
}
private InputStream iStream;
private OutputStream oStream;
private static final String TAG = "ChatHandler";
#Override
public void run() {
try {
iStream = socket.getInputStream();
oStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int bytes;
handler.obtainMessage(WiFiServiceDiscoveryActivity.MY_HANDLE, this)
.sendToTarget();
while (true) {
try {
// Read from the InputStream
bytes = iStream.read(buffer);
if (bytes == -1) {
break;
}
// Send the obtained bytes to the UI Activity
Log.d(TAG, "Rec:" + String.valueOf(buffer));
handler.obtainMessage(WiFiServiceDiscoveryActivity.MESSAGE_READ,
bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] buffer) {
try {
oStream.write(buffer);
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
}

Send instruction to arduino through micro usb in android phone via app

I want to send an instruction to Arduino through an android app over the micro USB port.
For example, on clicking a button in the app there should glow an led connected to Arduino and the connection should be done via the micro USB port on android phone. I've done the same using bluetooth connection. How should I proceed on this? Or what should be the changes in the code?
Via bluetooth:
package com.example.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
int red_count=0;
int yellow_count=0;
int green_count=0;
int white_count=0;
private static final String TAG = "bluetooth2";
Button red_button,yellow_button,green_button,white_button,reset_button;
Handler h;
final int RECIEVE_MESSAGE = 1; // Status for Handler
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "20:13:01:18:05:08";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
red_button = (Button) findViewById(R.id.red_button);
yellow_button = (Button) findViewById(R.id.yellow_button);
green_button = (Button) findViewById(R.id.green_button);
white_button = (Button) findViewById(R.id.white_button);
reset_button = (Button) findViewById(R.id.reset_button);
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
sb.delete(0, sb.length()); // and clear
red_button.setEnabled(true);
yellow_button.setEnabled(true);
green_button.setEnabled(true);
white_button.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
red_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
red_count++;
yellow_count=0;
green_count=0;
white_count=0;
red_button.setText(""+red_count);
yellow_button.setText("");
green_button.setText("");
white_button.setText("");
mConnectedThread.write("1"); // Send "1" via Bluetooth
}
});
yellow_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
yellow_count++;
red_count=0;
green_count=0;
white_count=0;
yellow_button.setText(""+yellow_count);
red_button.setText("");
green_button.setText("");
white_button.setText("");
mConnectedThread.write("2"); // Send "2" via Bluetooth
}
});
green_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
green_count++;
red_count=0;
yellow_count=0;
white_count=0;
green_button.setText(""+green_count);
red_button.setText("");
yellow_button.setText("");
white_button.setText("");
mConnectedThread.write("3"); // Send "3" via Bluetooth
}
});
white_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
white_count++;
red_count=0;
green_count=0;
yellow_count=0;
white_button.setText(""+white_count);
red_button.setText("");
green_button.setText("");
yellow_button.setText("");
mConnectedThread.write("4"); // Send "4" via Bluetooth
}
});
reset_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
white_count=0;
red_count=0;
green_count=0;
yellow_count=0;
white_button.setText("");
red_button.setText("");
green_button.setText("");
yellow_button.setText("");
mConnectedThread.write("0"); // Send "0" via Bluetooth
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10){
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (SecurityException e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}
/*try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
}*/
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try {
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "...In onPause()...");
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
errorExit("Fatal Error", "Bluetooth not support");
} else {
if (btAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message){
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
}
Ok,first of all i don't know anything about adruino coding,but in-order to communicate with usb devices android uses USB Host Api,goto the link for that.and here is a tutorial that may help interfacing android with Adruino,
how to communicate between the Arduino Uno and your computer using plain USB bulk and control transfers
Hope this helps

How recognize different URL requests to perform different actions using Android

I am trying to implement code that can recognize different URL requests and perform different actions upon each request, for example, take picture by accessing http://192.168.0.120/pic , and send email by accessing via http://192.168.0.120/email
I already built the code for taking picture and sending email but not sure how to assign them to different URL requests?
I found one code that can run a web server to recognize only one IP address and i want to to modified it to recognize multiple IP addresses and perform different actions upon each request:
The Code:
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class Server extends Thread {
private ServerSocket listener = null;
private static Handler mHandler;
private boolean running = true;
public static LinkedList<Socket> clientList = new LinkedList<Socket>();
public Server(String ip, int port, Handler handler) throws IOException {
super();
mHandler = handler;
InetAddress ipadr = InetAddress.getByName(ip);
listener = new ServerSocket(port,0,ipadr);
}
private static void send(String s) {
Message msg = new Message();
Bundle b = new Bundle();
b.putString("msg", s);
msg.setData(b);
mHandler.sendMessage(msg);
}
#Override
public void run() {
while( running ) {
try {
Socket client = listener.accept();
new ServerHandler(client).start();
LockStatus.getInstance().setMyVar(true);
clientList.add(client);
} catch (IOException e) {
}
}
}
public void stopServer() {
running = false;
LockStatus.getInstance().setMyVar(false);
try {
listener.close();
} catch (IOException e) {
}
}
Thanks a lot
Here is the modification of the code, but still cannot recognize the IP address:
public void run() {
try {
serverSocket = new ServerSocket(SERVERPORT);
while (running) {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String line = null;
String IP = "192.168.0.111";
line = in.readLine();
if (line.equals(IP)) {
new ServerHandler(client).start();
LockStatus.getInstance().setMyVar(true);
Log.i(TAG, "IP Receive=" + line);
// Toast.makeText(getContext(), "Matches",
// Toast.LENGTH_SHORT).show();
} else {
Log.i(TAG, " IP not received :=" + line);
// Toast.makeText(getApplicationContext(), line +" != "+
// IP, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

Categories

Resources