Bluetooth communication between Processing Desktop and Android(Not Processing) - java

What I'm doing is communication between
Desktop(Windows 8) Processing(2.2.1) Application <---- Android application(Not made by Processing, it's made on Android Studio)
I need to send data to desktop from android application (one side communication).
From android..
First, I'm getting already paired device. It means that before executing both application, I will pair desktop and android device already.
Bluetooth connection and sending outstream is on child thread.
Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
Log.i(TAG, device.getName() + "\n" + device.getAddress());
targetDevice = device;
break;
}
}else{
Log.i(TAG, "No paired device found!");
}
And then, I connect it
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = targetDevice.createRfcommSocketToServiceRecord(MY_UUID);
Method m = targetDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
tmp = (BluetoothSocket) m.invoke(targetDevice, 1);
} catch (Exception e) {
Log.e(TAG, "create() failed", e);
}
btSocket = tmp;
if (btSocket != null){
// Socket is created
// try to connect the socket
BluetoothConnectionThread thread = new BluetoothConnectionThread(btSocket);
thread.start();
}
From logcat(Log.i), I can see connection is successfully established. It seems that there is no problem on android side.
I'm using Serial Port Protocol UUID which is
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
And from Android side, it's completely ready to write any byte[].. and when I press dummy button on android, device sends dummy bytes to outputstream. I think it has no problem here on Android side..
Now, on desktop processing(Windows 8, processing 2.2.1 - I HAVE TO USE processing 2.0, there is no other option for some reason.), I have no any clue what I have to now.. I searched in google a lot but I could not find any clue. Now, I'm trying to use processing Serial library like
println(Serial.list());
but it gives nothing... So, I tried to initialize Serial object by
Serial port = new Serial(this, "/dev/rfcomm0", 115200);
but it gives error
Error opening serial port /dev/rfcomm0:Port busy
Is there any other way to read socket buffer(instream) which comes from Android on processing desktop?
I am sure that this is not bluetooth driver issue because I installed the recentest driver for my desktop(Qualcomm Atheros AR3012 Bluetooth 4.0 + HS)
Just for reference..desktop is actually laptop with bluetooth(ASUS UX21E) and Android device is Galaxy Tab S(267.2mm, Octa-Core 2560x1600).
I think I have not enough knowledge about bluetooth... Please lead me to some way...

Related

How to get button press event from camera

I've got a dental camera and iam try to get windows to press space when the camera button is pressed
I have the OEM software and driver installed, it works perfect, gets the feed and makes a snapshot when camera button is pressed. I need to use another software for the feed and the snapshot, the software gets the feed but doesn't react to camera button, it only reacts to space key press(part of the oem driver), so my way of solving this was getting the device by product id and listening the button press event and remapping it space press.
I am pretty much stuck at this point.
How can I listen on events coming from the device I've got?
public static Device findDCam(){
// Create the libusb context
Context context = new Context();
// Initialize the libusb context
int result = LibUsb.init(context);
if (result < 0)
{
throw new LibUsbException("Unable to initialize libusb", result);
}
// Read the USB device list
DeviceList list = new DeviceList();
result = LibUsb.getDeviceList(context, list);
if (result < 0)
{
throw new LibUsbException("Unable to get device list", result);
}
try
{
// Iterate over all devices and list them
for (Device device: list)
{
DeviceDescriptor descriptor = new DeviceDescriptor();
result = LibUsb.getDeviceDescriptor(device, descriptor);
if (result < 0)
{
throw new LibUsbException(
"Unable to read device descriptor", result);
}
if(descriptor.idProduct()== -3810){
System.out.println("D cam found");
return device;
}
}
}
finally
{
// Ensure the allocated device list is freed
LibUsb.freeDeviceList(list, true);
}
// Deinitialize the libusb context
LibUsb.exit(context);
return null;
}
I've also thought that maybe it's impossible using usb4java since as far as i understood, if i want to listen on the usb port i need to take control from the driver and then its pointless.
Maybe iam going all wrong and i should use the driver instead?
Or maybe there is an app that can read button presses from a specific device and remap it?
If the camera has a standard driver, this should work through this video capture SDK. To quick test it, run the demo executable included in the package, select the camera in the list, check the "webcam snapshot button" checkbox and start the camera. Then press the camera button to test the snapshot.

Arduino to Android Adb(Microbridge) recieves lets app crash, but sending data is ok

I'm using an Arduino with a USB hostshield (sparkfun) that is connected to a Android Phone. When I send data from the smartphone to the arduino then there is no problem. But when I send data from the arduino to the Android smartphone then the data is recieved (I get a message that the handler is triggerd) but the app crashes after a few cycles. I use de Adb library form Microbridge.
The data that is send from the arduino is as uint16_t with the number 800, this happens in the following loop (setup also included):
void setup()
{
Serial.begin(57600);
// Record time for sensor polling timer
lastTime = millis();
// Init the ADB subsystem.
ADB::init();
// Open an ADB stream to the phone's shell. Auto-reconnect. Use port number 4568
connection = ADB::addConnection("tcp:4568", true, adbEventHandler);
Serial.println("Ready!");
}
void loop()
{
//Check if sensor should be sampled.
if ((millis() - lastTime) > 1000)
{
int number = 800;
uint16_t data = number;
Serial.println("Before send");
connection->write(sizeof(data), (uint8_t*)&data);
Serial.println("After send");
// Update timer for sensor check
lastTime = millis();
}
// Poll the ADB subsystem.
ADB::poll();
}
The data is recieved on the Android in the handler as followd (it uses the lightwight server from Microbridge):
server.addListener(new AbstractServerListener() {
#Override
public void onReceive(com.example.communicationmodulebase.Client client, byte[] data){
Log.e(TAG, "In handler!");
if (data.length < 1){
return;
}
TextView textRecvStatus = (TextView) findViewById(R.id.RecvStatusText);
textRecvStatus.setText("In handler!");
}
});
The message: "In handler!" is shown but after a few recieves the app chrases.
Does anyone have a idea why the app crashes? I can't read the catlog since the Android smartphone is connected to the arduino shield. As far as I know there is no way to show the catlog data(I could be wrong).
Any suggestions and tips are welcome!

Unable to connect to FTP in Android

I've checked the other answers and they didn't help me with this error. Maybe I'm doing something else wrong.
Here's my code:
void uploadPic() throws FileNotFoundException
{
FileInputStream fis = new FileInputStream(path);
FTPClient con = new FTPClient();
int bytesAvailable;
try
{
con.connect("ftp://ftp.drivehq.com/");
Toast.makeText(this, "Connected to FTP", Toast.LENGTH_SHORT).show();
if (con.login("x", "x"))
{
Toast.makeText(this, "Logged in", Toast.LENGTH_SHORT).show();
con.enterLocalPassiveMode(); // Active mode doesn't really work on Android
bytesAvailable = fis.available();
byte[] barray = new byte[bytesAvailable];
fis.read(barray);
ByteArrayInputStream in = new ByteArrayInputStream(barray);
boolean result = con.storeFile("/CameraUpload.jpg", in);
in.close();
if (result) Log.v("Upload Result", "Succeeded");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
I've added INTERNET permission to my project.
The logcat shows these errors:
android.os.NetworkOnMainThreadException
W/System.err(17531): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
W/System.err(17531): at java.net.InetAddress.lookupHostByName(InetAddress.java:391
I'm connected to the internet via Wifi.
That exception seems to be thrown when you try to perform network operations (such as FTP) from your main thread. This is not allowed for performance reasons (so that the application doesn't appear to lock up to the user, when performing an action which may take a while). Assuming you are using Honeycomb or higher, you would need to move the code that makes the connection into its own child thread.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
http://developer.android.com/guide/practices/design/responsiveness.html
Most likely, this error means that your device cannot resolve ftp.drivehq.com to its IP address. I can't say for sure because you only pasted part of the error log. Make sure you have network connection and that your DNS is working correctly. See if you can connect to this same site via android browser, for example.

How to read and write data to COM/Serial ports in Android? [duplicate]

This question already has answers here:
using serial port RS-232 in android?
(8 answers)
Closed 2 years ago.
I have to read and write data to the COM ports of a device using Android. I am using javax.comm package for that, but when I installed the apk file, it is not displaying any ports of the device. Is there any permission which I need to add in the manifest file?
Your problem is one with operating systems. Android runs Linux under the hood, and Linux treats serial ports differently than Windows does. javax.comm also contains win32com.dll, a driver file, which you won't be able to install on an Android device. If you do find a way to achieve what you're trying to do, you can't actually look for a "COM" port in a Linux environment. The serial ports will go by different names.
Windows Com Port Linux equivalent
COM 1 /dev/ttyS0
COM 2 /dev/ttyS1
COM 3 /dev/ttyS2
So, hypothetically, if your idea were to work, you have to look for these names.
Luckily for you, Android does have provisions for interfacing with USB devices (Which I assume you want to connect to, as opposed to parallel or RS-232 ports). To do this, you will set up your device as a USB Host. Here's what you'll want to do:
Get a USBManager.
Find your device.
Get the USBInterface and USBEndpoint.
Open a connection.
Transfer data.
Here's my rough estimate of how you'll do it. Your code will, of course, have a more mature way of doing things.
String YOUR_DEVICE_NAME;
byte[] DATA;
int TIMEOUT;
USBManager manager = getApplicationContext().getSystemService(Context.USB_SERVICE);
Map<String, USBDevice> devices = manager.getDeviceList();
USBDevice mDevice = devices.get(YOUR_DEVICE_NAME);
USBDeviceConnection connection = manager.openDevice(mDevice);
USBEndpoint endpoint = device.getInterface(0).getEndpoint(0);
connection.claimInterface(device.getInterface(0), true);
connection.bulkTransfer(endpoint, DATA, DATA.length, TIMEOUT);
Extra material for your reading pleasure: http://developer.android.com/guide/topics/connectivity/usb/host.html
I am no expert, but for all those who are looking to connect serial RS-232 ports or open a serial port and can't find their device trough the UsbManager, you can find all your devices using an approach like this:
mDrivers = new Vector<Driver>();
LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
String l;
while ((l = r.readLine()) != null) {
String drivername = l.substring(0, 0x15).trim();
String[] w = l.split(" +");
if ((w.length >= 5) && (w[w.length - 1].equals("serial"))) {
mDrivers.add(new Driver(drivername, w[w.length - 4]));
}
}
After finding all drivers, iterate trough all the drivers to get all of your devices, using something like this:
mDevices = new Vector<File>();
File dev = new File("/dev");
File[] files = dev.listFiles();
if (files != null) {
int i;
for (i = 0; i < files.length; i++) {
if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
Log.d(TAG, "Found new device: " + files[i]);
mDevices.add(files[i]);
}
}
}
Here is the Driver class constructor, with two member variables:
public Driver(String name, String root) {
mDriverName = name;
mDeviceRoot = root;
}
For opening a serial port you can use the Android SerialPort API. Simply open the serial port at your device and write. (You must know your device path and baud rate. For example, my device is ttyMt2 with baud Rate 96000.)
int baudRate = Integer.parseInt("96000");
mSerialPort = new SerialPort(mDevice.getPath(), baudRate, 0);
mOutputStream = mSerialPort.getOutputStream();
byte[] bytes = hexStr2bytes("31CE");
mOutputStream.write(bytes);
Instead of wasting time on this code, you can download the complete project from https://github.com/licheedev/Android-SerialPort-Tool.

BlueCove Bluetooth Device Discovery

I've built and ran the RemoteDeviceDiscovery sample project for BlueCove 2.1.1. The program will discover all discoverable bluetooth devices but it will also report in deviceDiscovered() devices that were once paired before.
Is there a way to ONLY discover devices around you (like in Android)? The code below returns BOTH discovered devices and paired devices...
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
System.out.println("Device " + btDevice.getBluetoothAddress() + " found");
devicesDiscovered.addElement(btDevice);
try {
System.out.println(" name " + btDevice.getFriendlyName(false));
} catch (IOException cantGetDeviceName) {
}
}
Yes - use http://bluecove.org/bluecove/apidocs/javax/bluetooth/RemoteDevice.html#isTrustedDevice() to filter unpaired devices (or paired devices if you wish to).

Categories

Resources