Android, Bluetooth, catching special commands from BT device - android

How can we listen for special BT device commands like redial from our app? For now, I'm only able to listen to the only one - play/pause/start/end call button (KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE).
Using common BroadcastReceiver for "android.intent.action.MEDIA_BUTTON" doesn't help.
Solution with BluetoothSocket, BluetoothServerSocket won't help too since it requires our code to be invoked on BT device side.
During my redial button tests I see the next line in the logs:
01-20 05:52:30.486 942-1060/com.android.bluetooth E/bt-rfcomm: PORT_DataInd, p_port:0x5526c200, p_data_co_callback is null
It looks like there is something sending an event from BT device to the android device. But how can we catch it on app side, what should we use? I work on some system app by the way and theoretically can do very specific, low-level and system things, so maybe there could be some solution.

afaik, this isn't possible, sadly...
I've been working on custom handling BT headset keys, like VOL UP, DOWN, eventually ANSWER/DISCONNECT/REDIAL. Even made rich question, but without single answer or comment...
After some research (days, weeks...) and digging into Android source I've found that these buttons are sending some AT commands. I've also found methods which are checking these AT commands and if system is able to respond/handle them then it TRY to do it and further won't pass any event to any app/socket/rfcomm/anything... E.g. under VOL UP button we have some well-known AT command, system can handle it, so try to do so, even when we already have volume set to max. Any app won't be noticed that this happened...
btw. I don't think this logcat line posted in question is strictly relevant to button press (but may be indirectly), but you have bt-rfcomm keyword in there, so you may try to establish some RFCOMM connection with Bluetooth device, maybe you will get some luck on this topic... (personally I gave up...)

Related

Error codes in Nearby Connections 2.0

I've been experimenting with the new Android Nearby Connections v2.0 API. Most of my devices can now talk to each other most of the time, but I also get a lot of error codes back when trying to connect. Checking status.getStatusCode() inside my program, I can see the following return codes:
STATUS_ALREADY_CONNECTED_TO_ENDPOINT (8003)
STATUS_BLUETOOTH_ERROR (8007)
STATUS_ENDPOINT_IO_ERROR (8012)
STATUS_ERROR (13)
I'm having a hard time making sense of these. The first error code seems self-explanatory, except that I see it in cases when I haven't hit the onConnectionResult callback with a "SUCCESS" return code on either side of the alleged connection. My current code is full of trace statements, and I'd see logging entries if those callbacks had been reached. So maybe the devices are connected at some lower level, but if so, the higher-level code doesn't always hear about it.
I'm guessing that STATUS_BLUETOOTH_ERROR indicates a Bluetooth error on the side that logs it, while STATUS_ENDPOINT_IO_ERROR indicates an error (probably involving Bluetooth) on the other end? Is it possible to get any more details?
The STATUS_ERROR (13) status that I see once in a while sounds like the sort of error code a programmer would use for those "WTF, we should never get here" moments, but without access to the source code, I can only guess.
Note that I see these errors between devices that talk to each other beautifully at other times, using the same code. Sometimes if the code retries enough times, it eventually gets a stable connection. Sometimes it connects and gets instantly disconnected from the other end. Sometimes I just get an endless stream of repeated error messages (STATUS_BLUETOOTH_ERROR and/or STATUS_ENDPOINT_IO_ERROR).
I'm using Nearby Connections with the connection strategy P2P_CLUSTER. These problems seem to happen most often when both sides do both advertising and discovery. However, I wrote two smaller programs that specialize in either advertising or discovery, and they sometimes get these errors too (but less often).
In the trace messages, I've also noticed lots of warning messages from Nearby Connections that look like this:
09-04 22:54:40.070 3866-3924/? W/NearbyConnections: Cannot deserialize BluetoothDeviceName: expecting min 16 raw bytes, got 6
I'm guessing that this is because Nearby Connections uses its own short tokens (like ZGbx) instead of the device Bluetooth name? I'm not at all sure about that, though. And anyway, if these are Nearby Connections' own special tokens, then why would it be issuing warning messages about it?
[Disclaimer: I work on Nearby Connections] I can try and help out.
STATUS_ALREADY_CONNECTED_TO_ENDPOINT: This occurs if you call 'requestConnection' while you have any pending (onConnectionInitiated) or established (onConnectionResult) connections to the given endpoint. Move your log statements earlier, to onConnectionInitiated, and you should see why we throw this error.
STATUS_BLUETOOTH_ERROR: Something went wrong with Bluetooth. The phone is probably in a bad state. This (hopefully) shouldn't happen too often. But if you really want a fix, stop advertising & discovery before reattempting requestConnection. Nearby Connections will toggle Bluetooth when it detects this error, but only if nothing else is going on.
STATUS_ENDPOINT_IO_ERROR: We lost connection to the other device. This can happen for a variety of reasons (they could have walked too far away, Bluetooth was flaky, the device stopped responding, etc). If you're discovering while you have connections, avoid that. Discovery can be hard on the phone and reduces bandwidth at best, causes dropped connections at worst.
STATUS_ERROR: Something went wrong that didn't fit well in the other error codes. It's a catch-all. This is most-often returned in onConnectionResult(FAILED), to notify you that something went wrong in between onConnectionInitiated and waiting for both sides to accept the connection.
We've also lowered the log severity of "Cannot deserialize BluetoothDeviceName" in an upcoming release, since it's not really a warning. It's like you said; expected behavior when we see non-Nearby Connections devices while discovering.
If you continue to see problems, let us know what devices you're using and we'll be sure to add them to our test suite.
I just want to add that it may be necessary to have a short client name string when calling the API.
E.g., Nearby.Connections.requestConnection(googleApiClient, shortNameHere,....)
I had been generating my own client name with UUID.randomUUID().toString() and that seemed to cause the STATUS_BLUETOOTH_ERROR.
All I did was change the code sample to use a UUID name and to use P2P_CLUSTER and I got that error.
This was the solution for me regarding the STATUS_BLUETOOTH_ERROR.

Bluetooth SPP: Bluetooth SPP Pro (Android) vs. Microchip SmartData (iOS)

All,
I am attempting to communicate, over an SPP profile, with an RN4678 Bluetooth chip connected to a microcontroller.
I never have a problem with the Android app. I can always pair (if not paired), connect, send messages to the chip, and disconnect. An example session is below:
%CONNECT,AB9876543210%
%RFCOMM_OPEN%
%TEST% <-- Message sent using the keyboard ("Byte Stream Mode" option)
%RFCOMM_CLOSE%
%DISCONN%
With the iOS app, I can always pair (if not paired), connect, and disconnect. However, if I cannot send a message to the chip. An example session is below:
%LCONNECT,499B107AB1B5,1%
%LSECURED%
<-- Here I try to send a message, but it is never received
%DISCONN%
The funny thing is that if I first connect/disconnect using the Android, and then I connect using the iPhone/iPad, reception is successful !!!!
%LCONNECT,499B107AB1B5,1%
%LSECURED%
%TEST% <-- Yeah !!! Microcontroller receives the message
%DISCONN%
As far as I know, that path for the processing is the same ... In other words:
if(msg equals "RFCOMM_OPEN" or msg equals "LSECURED")
go to state that monitors incoming messages
I, therefore, kindly ask the following:
1 - Have you encountered anything similar? Do you have any hints? What could the Android App possibly do that the iPhone app is not doing? What am I overlooking or not understanding?
2 - Are you aware of an app that works for both iOS and Android? What I mean, designed by the SAME guy/company?
If you need more info, please ask. I simply did not want to be too 'verbose'.
Thank you for your assistance.
Sincerely,
Vincenzo
All,
At my job we have been playing with two RN modules: the RN4677 (we started with this module) and the RN4678.
The module allows the user to enter (and exit) a command mode. The RN4677 allows bidirectional communication with a manager while still in command mode. The RN4678 does NOT allow bidirectional communication with a manager while still in command mode.
All I needed to do was exit command mode (by issuing the command '---\r'). Now both modules work with Windows/Android/iOS ...
To summarize:
command "$$$\r" to enter command mode
various commands, requests for settings, ...
command "---\r" to exit command mode (a must for RN4678)
Everything will now work fine for both modules
I must say ... that was painful to troubleshoot ...
Sincerely,
Vincenzo

How to calculate when the network card opens a connection on Android

I am trying to figure out if there is a way to know when an app opens an internet connection and thus wakes up the network card.
So for example, I have the phone off and I decide to search http://www.cnn.com
In this case, lets imagine that no background data is going on from any app, so the connection is IDLE at the time I call the website. I want to know when the network card opened the connection to load the page.
I have found no APIs for this. Originally I was looking at the TelephonyManager which has different states of the network card (DORMANT, INOUT, NONE, etc), but I found my phone never goes to dormant, I believe this is due to fast dormancy. I have also been looking at linux filesystem files that might contain this information from the driver, but I have found none.
I read this nice article from ATT which explains about mobile networks
http://www.research.att.com/articles/featured_stories/2011_03/201102_Energy_efficient?fbid=xEv4RTIfUL9
Thanks.
Ok so the answer is to use the SignalStrength class and the PhoneStateListener's onSignalStrengthsChanged in order to measure the radio signal. This helps detect when a connecdtion is made. Referenced from ATT's ARO app:
https://developer.att.com/application-resource-optimizer
http://developer.android.com/reference/android/telephony/SignalStrength.html
http://developer.android.com/reference/android/telephony/PhoneStateListener.html#onSignalStrengthsChanged(android.telephony.SignalStrength)

Android Bluetooth IOException:connection refused

Alright here's the deal. I got two Galaxy Nexus phones both with bluetooth enabled.
I've written a bluetooth connection management app that I use for device discovery and connectivity. It also outputs all the available UUIDs the devices can support.
Looking from http://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm the following standard UUIDs are exposed from Galaxy Nexus devices.
0x1116 - NAP
0x112f - PBAP (Phonebook Access Profile)
0x111f - HFP (Hands free)
0x1105 - OPP (Object Push Profile)
0x1112 - HSP (Headset Profile)
0x110c - AVRCP
0x110a - A2DP
I am trying to connect via the OPP profile (UUID 00001105-0000-1000-8000-00805F9B34FB) and push objects (files) between the devices. I've gone though the entire Android API documentation on how to discover, pair/bond (threading etc.) and manage all bluetooth connections. I've managed to successfully connect and talk to a legacy board device via the SPP (0x1101) profile.
However, when I try to use socket.connect() between the two galaxy nexus phones, the pairing dialog shows up and I click Pair button on both devices. After that, I immediately get a Connection Refused IOException. Note that after pairing has occurred once I never get asked again which makes sense since the secure link is cached.
If I can't connect to these standard profiles using these standard UUIDs why are they exposed? How can I connect from my app to any of these profiles and interact with them? Is it because my app is not somehow trusted? What's weird is that even the Share functionality on Android does not work at all either. Is this something completely broken on Android?
Please avoid giving me hints to use the "well known UUID SPP one 0x1101" like the docs say. This is not what I want. I have a fairly good understanding of how this stuff works and I am looking for a real solution or explanation of the problem.
I've seen the typical "reflection" solution but I do not understand why is this still a problem on Android? Why do people use reflection to make this work? Can we file a bug on Android to fix this?
If those UUIDs are standard any app should be able to connect and interact with them. Why is this an issue and why do I get this exception?
Thanks in advance.
UPDATE
So for some reason the object push in the Android system started working. I actually attempted to connect via my app and it was not working. Then, I went to the Contacts app and tried to share a contact which magically worked. Then, I went back to my app and it now it works...wow. That is very weird and there must be an explanation to this.
I ran into this same issue and managed to find a solution that worked for me.
In my case I using three different test devices (Nexus 5, Galaxy S4, Note 2) and for some reason, the Note 2 wouldn't connect to my Bluetooth module yet the other two would.
The reasoning I've found is that Bluetooth drivers vary, and slightly different connection methods are needed to create a connection between different devices.
The three methods I use are called 'Secure', 'Insecure' and 'Reflection method'/'hax'.
switch(connType)
{
case Secure:
tmpSocket = device.createRfcommSocketToServiceRecord(_uuid);
break;
case Insecure:
tmpSocket = device.createInsecureRfcommSocketToServiceRecord(_uuid);
break;
case Hax:
Method createSocket = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmpSocket = (BluetoothSocket)createSocket.invoke(device, Integer.valueOf(1));
break;
}
In my case, the Secure mode worked for both the Nexus 5 and Galaxy S4 however it didn't work for the Note 2.
After some testing I discovered the Note 2 only works using 'Insecure' mode, so to cater to this, I basically attempt a connection and cycle through the different modes if necessary. When attempting a different connection mode I simply prompt 'retrying connection'. So, if the connection fails using secure, then I will attempt using Insecure and then using the reflection method.
I haven't run into the case where one of these three methods haven't worked.
Have you tried using a nonstandard profile? i.e. a custom UUID just for your app. This will also help you know your are (most likely) only connecting to your own app rather than some other app that is registered with the same profile.
From my experience, Bluetooth pairing is very buggy for the first pair attempt. However, using a custom UUID helps this somewhat.
The reflection method (I think) was originally an attempt to fix a bug with a specific device, however I think some people found success in using it elsewhere as well. The device was called the Spica or something similar.
As one of the comments also posted, I would also try connecting again after failing.
Basically write code that plans to fail the first attempt, but then the code tries to connect again in 5 seconds if there was a failure.
These are imperfect solutions but Bluetooth implementation on Android is also imperfect (IMHO). Hope that helps
EDIT
Based on the question update and comments:
I agree something is definitely buggy. Part of the problem I think is the BT drivers vary and each has a different BT stack with different quirks. I also found a question that makes use of both the reflection method AND custom UUID, AND other standard methods. This seems extreme to me but it does cover the most ground. Unfortunately as app developers we have no control over the low level stack/code/drivers.
I have found with my two Bluetooth sharing apps that the first pairing is always tricky.
I'm glad to know it's not just me.

Writing a GSM emulator for use with Android

For some work I'm doing, I want to have an emulated GSM modem which will communicate with an Android-x86 virtual machine over a Unix socket. The VM should see the emulator as a real modem and use it to send SMS (as the first pass of functionality).
So far, I've put something together which handles some AT commands and just replies "OK" to all the rest. For some commands, like "AT+CRSM", I just have a table of responses gathered from running the official Android emulator and looking at the radio log. For others, I maintain some state and construct answers; those commands include:
CFUN?
CPIN?
CGREG?
CGREG?
COPS?
CGREG=
CREG=
CPIN=
COPS=
CRSM=
CSMS=
CGSN
CIMI
CSQ
Android will boot, and send commands to my emulated modem, which answers, however it doesn't seem to be fully functional. Android doesn't detect any radio signal strength, for instance, just showing an "x" in the signal bar.
Does anyone know of a similar project, or just what AT commands are absolutely necessary to get some basic functionality?
Well, I'll answer another of my own questions, it's easier that way.
I ended up implementing an emulator which maintains a little bit of state, such as whether or not unsolicited CREG and CGREG messages are enabled, the network registration status & network name format (for the COPS command), and a message reference counter for SMS.
It supports the following commands:
CFUN?
CPIN?
CGREG?
CREG?
COPS?
CGREG=
CREG=
CPIN=
COPS=
CRSM=
CSMS=
CMGS=
CGSN
CIMI
CSQ
All other messages just get an "OK" response.
With the stock AOSP Android source running in an emulator with the "-radio unix:/tmp/phone" switch, I can send SMS messages and decode the binary PDUs into real messages. I will continue to add functionality so SMS messages can be injected back to Android, and hopefully open-source the code at some point.

Categories

Resources