Sending Data via Bluetooth - android

I'm a little confused about how to send data over a Bluetooth connection. In the Android API documentation, from the Bluetooth Chat example, the class BluetoothChat.java constructs a Handler object. Within there is a switch statement, and a MESSAGE_WRITE case. Do I need to implement similar code to send Strings over Bluetooth? A case statement for each String I want to send? In particular I want to send (name,value) pairs so I know what is sent and what it's value is. How do I implement this? If, following the example, I call BluetoothChatService.write(String.getBytes()) a bunch of times to send...? Then how would I know which strings are associated with which names? Please help.

I'm using Google's Protocol Buffers to send structured data over bluetooth connections in my Android app. protobuf takes care of figuring out how to serialize the message for you so that you only have to send a byte value (length of the message) and then the serialized message; the library takes care of unserializing the message on the other end and populating the fields of a custom object. Definitely take a look at it; it made the writing of a custom bluetooth socket protocol quite easy.

Serialize pairs to any of formats which allows byte representation. Such as XML or JSON. Or even your custom format, it wouldn't be difficult for pairs of strings. And then send it.

For simple pairs of strings (Such as names), you could simply use some character to define when the first string stops, and the next begins.
For example, I use a format such as this to send a set of 3 strings from one device to another:
String toSend = partOne + ":" + partTwo + ":" + partThree;
On the other device, to get the strings you sent, use the String.split() method like so:
String parts[] = received.split(":",3);
The 2nd parameter is a limit to how many times to split. In this example, there are 3 strings, so split 3 times max.
The downside to doing this is that you need to use characters that will never be in all but the last string.
In my application, I used this method to send data about text messages, and the first 2 parts are the phone number and timestamp, so there can never be a : in it. For names, a newline would probably work.
If your going to send more complex data, definitely use something like Protocol Buffers.

Related

Android Parse a JSON String With Quotes in Keys and Values

Android JSON parsing is rather straightforward until it comes to have json reserved characters in your keys/values. I have JSON coming from an HTTP socket whose response is put into a string variable. It looks like this
{"ZboAdtPw4bA":"Ben Heck"s PlayStation 4 Slim Teardown","iC4qIx72_Cc":"Ben Heck's Xbox Slim Teardown"}
See the double quotation in the first value? It even screws up on StackOverflows web page. How am I supposed to escape/prevent this from happening? If I do a:
response = response.replace("\"", "");
Then all the double quotation get replaced, not just the ones in the key/value pair. This is because its all contained in one string at the moment. I am wondering if there is an easy way to do this with android. And of course, java answers are acceptable to. Now I could do this since its just a single dimensional key/value pair easily, I may not even need JSON, but I would like to adhere to standards.
you are simply trying to ruin the basic of a JSON .
you simply add
"/"" to the java code .
other than that its not possible for the parser to differentiate between the quotations from the JSON format or the quotations in the string .

Android Wear: How to send multiple items with MessageApi?

So i want to use the MessageApi and not the DataApi to send multiple items to the wearable. However the sendMessage() of the MessageApi only allows a byte array to be sent.
For reference:
Wearable.MessageApi.sendMessage(mGoogleApiClient,
String id,
String path,
byte[] bytes)
My guess would be to create an array of byte arrays and then serialize that into one big byte array and send it off.
To make things clearer these are the steps in pseudo code:
byte[][] arrayOfByteArrays;
String a --> convert to byte[];
Bitmap b --> convert to byte[];
Add a and b byte[]'s to arrayOfByteArrays;
Serialize arrayOfByteArrays to just a byte[] and send it off;
Is this the correct approach? or Should I just call sendMessage() multiple times? Thanks.
In general, it is more efficient (battery, bandwidth, ...) to send one message instead of multiple ones. However, there may be other factors involved in your specific case that may warrant sending multiple messages. Looking at your pseudo code, I noticed you are also trying to send a bitmap using the MessageApi. That, in general, is not the best approach to send across an image, or other types of assets; you can use Assets or you can use ChannelApi. Otherwise, the approach of serializing a bunch of small objects and putting them into one byte array and then desrializing at the other end would work; one simple way to do so (if dealing with simple objects) is to use json as a serialization means.

Arduino --> Android bluetooth communication (receive text with App Inventor)

I'm creating an Arduino based drone that can be controlled through an Android application.
In order to improve the user experience, I'd like to show the accelerometer/compass sensor's values on the application, so I need to send them from Arduino to Android, via Bluetooth. The values are simple integer number between 0 and 180.
The best solution I thought is to concatenate all the values (separated with a comma) in one string, and send it to the app, that will separate the single values (the string will be sent only when the app require it, in this case when a 'z' byte is received by Arduino).
if (Serial.available() > 0) {
if (Serial.read()=='z'){
Serial.println(String((int)sensor1) + ',' + String((int)sensor2) + ',' + String((int)sensor3));
}
}
Here are the App Inventor blocks:
It seems that the values are being received quite well, but there is a critical issue: somethimes the string is not received well, and that cause a lot of errors. Sometimes the received string is (for example) 10,10,10, but somethimes it is 10,10,1010 or just 10,10 ecc...
I also tried to send the values one by one, but the result was nearly the same.
I even tried to set 'numberOfBytes' to -1, using a delimiter byte, but this also was not succesful unfortunately.
I getting quite mad, so I hope there is another way to send thoose integers to Android, or to fix the system I'm already using.
I used Serial.print to send each result and then used Serial.write('>'); as the end marker.
In appinventor designer window set the Delimiter byte for Bluetooth client to 62 (the ASCII value for the > character ).
In the blocks window, use Bluetooth cliant1.Receive text and set number of bytes to -1
App invented will then read until a delimiter is found.
However it will cause the app to hang if it doesn't find one.
the problem is that you are not signaling the end of the string
I used his example on a project and was something like this:
while(Serial.available()>0){
Serial.println(String((int)Sensor1) + ',' + String((int)Sensor2)+ ',');
}
If you compare the two codes the difference will be a " , " the most at the end of the print and it solved the problem for you sitad

How to send a list of items to the watch from PebbleKit for Android

I have an android app that is essentially a list of timers. Each timer can have the following fields:
title (string, can be up to 255 characters)
id (integer)
seconds (integer)
time_started (integer)
seconds_left (integer)
running (boolean)
order (integer)
There can be an unlimited number of these timers, though for the pebble watch app, it'd be ok if I only send the first n (10, 15, 20).
Currently I've been sending the items to the watch one at a time, and creating the PebbleDictionary like this:
private PebbleDictionary buildTimerDictionary(Timer timer) {
PebbleDictionary data = new PebbleDictionary();
data.addUint32(C.KEY_ID, timer.getId());
data.addUint32(C.KEY_SECONDS, (int)timer.getSeconds());
data.addString(C.KEY_DESCRIPTION, timer.getDescriptionFormatted());
data.addUint32(C.KEY_TIME_STARTED, (int)timer.getTimeStarted());
data.addUint32(C.KEY_TIME_LEFT, (int)timer.getSecondsLeft());
data.addUint8(C.KEY_RUNNING, (byte)(timer.isRunning() ? 1 : 0));
data.addUint32(C.KEY_ORDER, (int)timer.getOrder());
data.addString(C.KEY_TIME_DISPLAY, timer.getSecondsFormatted());
return data;
}
And sending it via a queue that sends the next PebbleDictionary to the watch after the previous is acked.
This works, but it's pretty slow. I feel like I could save a lot of time by packing more than one timer into each message. However, I'm not sure how to do that, considering the inbox size on the pebble watch itself, and the fact that you have to hard define the keys for the dictionary in appinfo.json (it doesn't seem like you can use arbitrary keys).
How is this sort of thing usually done?
There are two ways to do this:
One message for each item (what you are doing now)
Multiple items per message.
In this case you can pack everything into one value by using byte arrays and concatenating all your fields into the byte array.
You can then use the key to send the index of the element in the list.
A few comments:
Defining the keys in appinfo.json is optional and only useful if you are using PebbleKit JavaScript. It has absolutely no use for apps that talk with PebbleKit Android.
You can query the available buffer size on Pebble with app_message_inbox_size_maximum(). Get it when you start your app and send it from Pebble to the Android app.
The best strategy depends on the average size of your messages. Right now your items will be about 25bytes + the strings + the small overhead of a dictionary (7 bytes + 1 byte per key). If the strings are very small you might fit three items per messages, if the description is very long, you might not be able to send the item at all (you should probably truncate it).

How to get the particular value from the response message and assign it to another variable in the next request in Jmeter?

I am trying to make a performance testing process by using the Jmeter for the mobile chat application. The scenario i am trying is,need to analyze the output during the N number of new user registration process.I am feeding the N user data through "CSV Data Set Config".In that mentioned the variable names as "phone,ime".
For each new user registration process,the application will generate the one time password when calling the API1.The question is,I need to get that generated one time password from the API1 response message for each phone user and need to assign the value to the variable ${code} when calling the API2.
The below are the API & parameters details:
API1:/api/users/registration-sms.html?
1) Name:phone, Value: ${phone}
2) Name:ime, Value: ${ime}
Example :
Request - POST data: phone=917010370002 & ime=e78b56418b55b32c
Response:{"response":{"httpCode":200,"Message":"True","Code":"5858"}}
API2: /api/users/registration-sms-verfy.html?
1) Name:phone, Value:${phone}
2) Name:code, Value:${code}
Note : For this variable ${code},We need to get the data from the API1("Code":"5858") response message for the respective phone(917010370002).
Please provide me the feasible solution to sort out of my requirement.
Thanks in advance.
You can use Regular extractor post processor like,
Assuming your response is like
{"response":{"httpCode":200,"Message":"True","Code":"5858"}}
your regular expression will be like to extract code value but for specifiic phone no you need to modify it a little bit,
"Code"\:"(\d+)"
for occurance detail you can provide which match no. you want.
Refer Regular Expression Exctrator Post Processor

Categories

Resources