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;
}
}
Related
I have an app which has to poll a TCP server (on LAN) to fetch some data, I'm doing this using sockets in an AsyncTask class.
It works well for the first few requests. But at a certain point, the app must poll the server every 2s (using a timer). This is when the AsyncTask stops executing and the TCP messages do not get sent to the server. I can't figure out why.
Code is below. Any help will be appreciated!
Thank you!
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class TcpTask extends AsyncTask<String, Void, String> {
Context context;
TcpResultListener tcpResultListener;
int actionCode;
String TAG = "TcpTask";
String SERVER_IP = "192.168.1.12", SERVER_PORT = "1234";
Socket socket = null;
PrintWriter out;
int readTimeout;
// Creating listener
public void setOnTcpResultsListener(TcpResultListener tcpResultListener, int actionCode) {
this.tcpResultListener = tcpResultListener;
this.actionCode = actionCode;
}
// Constructor with context as parameter
public TcpTask(Context context, int timeout) {
this.context = context;
this.readTimeout = timeout;
}
#Override
protected String doInBackground(String... params) {
String result = null;
try {
//Create a client socket and define internet address and the port of the server
socket = new Socket(params[0], Integer.parseInt(params[1]));
Log.d(Constants.TAG, "Socket created");
//Setting timeout for readLine
socket.setSoTimeout(readTimeout);
Log.d(Constants.TAG, "Timeout set");
//Get the output stream of the client socket
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(Constants.TAG, "PrinterWriter created");
//Write data to the output stream of the client socket
out.println(params[2]);
Log.d(Constants.TAG, "Sending TCP data: " + params[2]);
//Get the input stream of the client socket
InputStream is = socket.getInputStream();
//Buffer the data coming from the input stream
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//Read data in the input buffer
result = br.readLine();
} catch (NumberFormatException e) {
Log.d("TcpException", e.toString());
} catch (UnknownHostException e) {
Log.d("TcpException", e.toString());
} catch (IOException e) {
Log.d("TcpException", e.toString());
}
try {
Log.d(Constants.TAG, "Socket:: " + socket);
if(socket != null){
socket.close();
}
} catch (IOException e) {
Log.d(Constants.TAG, e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
Log.d(Constants.TAG, "String:: " + result);
tcpResultListener.onResultsReceived(result, actionCode);
}
}
The method I use to call the AsyncTask:
void sendTCP(String msg) {
TcpTask tcpTask = new TcpTask(this, 8000);
// Setting listener for tcpTask to send back result
tcpTask.setOnTcpResultsListener(AddSpaceActivity.this, 1);
// TODO: Change the data being passed below
//Pass the server ip, port and client message to the AsyncTask
tcpTask.execute(gwIP, gwPort, msg);
}
EDIT: Timer code:
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d(Constants.TAG, "Timer fired:: " + firstReceived);
if(firstReceived){
sendTCP(Constants.NETWORK_STATUS_REQUEST);
}
}
}, 3000, 2000);
So I am about to pull my own skin off of my face this has been frustrating me so long. I am trying to capture data sent over Bluetooth and the Handler's handleMessage() method does not fire. Can anyone help?
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String BT_UUID = "a2cd7958-5745-450c-9dfc-48ad58ca8d95";
private static final int MESSAGE_READ = 999;
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice mDevice;
private BluetoothSocket mBluetoothSocket;
private Handler mConnectionHandler;
private RelativeLayout mConnectionLayout;
private static MainActivity mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
mDevice = intent.getParcelableExtra("device");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mConnectionLayout = (RelativeLayout)findViewById(R.id.connection_overlay);
mContext = this;
}
#Override
public void onResume() {
super.onResume();
attemptBluetoothConnection();
}
public void attemptBluetoothConnection() {
UUID uuid = UUID.fromString(BT_UUID);
try {
mBluetoothSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
Log.v("[bluetooth]", "creating RF Comm channel...");
} catch (IOException e) {
e.printStackTrace();
mBluetoothSocket = null;
}
new Handler().post(new Runnable() {
#Override
public void run() {
if (mBluetoothSocket != null) {
Log.v(TAG, "socket not null, attempting connection...");
try {
mBluetoothSocket.connect();
Log.d(TAG, "Connection made!");
mConnectionLayout.setVisibility(View.GONE);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
try {
Log.v(TAG, "Trying fallback");
mBluetoothSocket = (BluetoothSocket) mDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class}).invoke(mDevice, 1);
mBluetoothSocket.connect();
mConnectionLayout.setVisibility(View.GONE);
mConnectionHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.v(TAG, "[handleMessage]");
switch (msg.what) {
case MESSAGE_READ:
String data = new String((byte[])msg.obj, 0, msg.arg1);
Log.v(TAG, "Received Data: (" + data.length() + ") " + data);
}
}
};
mConnectionHandler.post(new ConnectedThread(mBluetoothSocket));
Log.v(TAG, "Connection made!");
} catch (Exception e2) {
e2.printStackTrace();
}
Log.d("Connection not made...", "");
}
} else {
Log.v("[bluetooth]", "socket is null...");
}
}
});
}
public class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
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();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
Log.v(TAG, "Reading InputStream...");
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
Log.v(TAG, "Sending to " + mConnectionHandler.obtainMessage().getTarget().toString());
mConnectionHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
This code worked perfectly up until I moved it into it's own separate activity when this started happening. Any help is appreciated. Thanks.
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
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);
I've finally managed to connect from my android phone to my device, put I have a problem when I try to read from my bluetooth socket.
So here is my code for establishing connecting to my device, its a class that extends AsyncTask
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
public class Connect extends AsyncTask<String, Void, String> {
private final static String TAG = "+++CONNECT THREAD+++";
ProgressDialog progressDialog;
Context context;
BluetoothSocket tmp;
BluetoothDevice device;
BluetoothAdapter ba;
Button connect;
int bt_port_to_connect;
ReadInput ri;
InputStream is;
byte[] test;
public Connect(Context context, BluetoothDevice device, BluetoothAdapter ba, Button connect) {
this.ba = ba;
this.context = context;
this.device = device;
this.connect = connect;
bt_port_to_connect = 9;
}
protected void onPreExecute() {
progressDialog=ProgressDialog.show(context,"Please Wait..","Connecting to device",false);
}
#Override
protected String doInBackground(String... arg0) {
Method m = null;
try {
m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(device, bt_port_to_connect);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ba.cancelDiscovery();
tmp.connect();
ri = new ReadInput(tmp);
ri.start();
} catch (IOException e) {
Log.e("+++CONNECT1+++","EXCEPTION: " + e.getMessage());
try {
tmp.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + " insecure socket type" +
" socket during connection failure", e2);
}
Log.e("+++CONNECT2+++", e.getLocalizedMessage());
}
boolean isConnected = tmp.isConnected();
if(isConnected) {
return "connected";
}
else {
return "notConnected";
}
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
if(result.equals("connected")) {
connect.setEnabled(false);
Toast.makeText(context, "Connected to device: "+device.getName().toString(), Toast.LENGTH_LONG).show();
//new ReadIn(context, tmp).execute("");
}
else if(result.equals("notConnected")) {
Toast.makeText(context, "Can`t reach host", Toast.LENGTH_LONG).show();
}
}
}
As you can see, the line below tmp.connect(); I create a new object of a new class, this is the class which I want to handle the reading of the inputStream So here is the code for that class:
import java.io.IOException;
import java.io.InputStream;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ReadInput extends Thread {
BluetoothSocket socket;
private InputStream is;
public ReadInput(BluetoothSocket socket) {
Log.i("READINPUT", "INSIDE READ INPUT THREAD CONSTRUCTOR!!!");
InputStream tmpIn = null;
this.socket = socket;
is = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Log.e("READINPUT", "Temp socket in created: " + e.getMessage());
}
is = tmpIn;
}
public void run() {
Log.i("READINPUT", "INSIDE READ INPUT THREAD RUN METHOD!!!");
byte[] buffer = new byte[1024];
int bytes = 0;
while(true) {
try {
bytes = is.read(buffer);
} catch (IOException e) {
Log.e("FROM RUN METHOD: ", e.getMessage());
}
Log.i("INPUTSTREAM GOT: ", Integer.toString(bytes));
}
}
}
I have two Log.i methods in my last code, this outputs the correct info to LogCat stating where in the code I am. But it doesnt output the content of the stream to LogCat. What am I doing wrong here? Yes, I've looked into the BluetoothChat example.
Thanks in advance!
EDIT 1
I've done some research in the constructor of the ReadInput Class.
is = tmpIn;
try {
Log.i("InputStream: ", Integer.toString(is.available()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This snippet will only output to logcat that is returns 0 which means that the InputStream is not available. Any suggestions?
I found using a buffered reader works well with a blietooth device. And then I just used a while.loop with br.isReady in a while true listener. Basically makes a "listener"