In my app i send four basic commands to OBD ports and get back hex data...
I don't know why if i send the command:
ME: 010c
Car: 10c410c0000
Why the message don't start with 4?
And get only 410c and the data that the obd receive from car?
I use this method for manage hex response and convert it to human readable data, and RawData is a String that take the message and clear all space, like this
41 0c 00 00 = 410c0000
public String getCalculatedResult() {
//TODO devo convertire i dati da esadecimale a decimale ed effettuare i calcoli
int calculatedData = 0;
String dataToShow = null;
//Log.d("ObdCommand", "rawData: " + rawData.substring(3));
calculatedData = Integer.parseInt(rawData.substring(7), 16);
if (Pattern.compile(Pattern.quote(rawData.substring(3,4)),
Pattern.CASE_INSENSITIVE).matcher("410D").find()){
Log.d("ObdCommand", "dentro 410D: ");
//Velocità veicolo km/h
dataToShow = String.valueOf(calculatedData) + " Km/h";
Log.d("ObdCommand", "rawData: " + dataToShow);
}else if (Pattern.compile(Pattern.quote(rawData.substring(3,4)),
Pattern.CASE_INSENSITIVE).matcher("410C").find()){
Log.d("ObdCommand", "dentro 410C: ");
//Giri minuto veicolo rpm
calculatedData = calculatedData/4;
dataToShow = String.valueOf(calculatedData) + " rpm";
}else if (rawData.substring(3).startsWith("4105")){
//Temperatura refrigetante C°
calculatedData = calculatedData - 40;
dataToShow = String.valueOf(calculatedData) + " C°";
}else if (rawData.substring(3).startsWith("4151")){
//Tipo di carburante
if (rawData.substring(7).startsWith("09")){
//Benzina
dataToShow = "Benzina";
}else if (rawData.substring(7).startsWith("0d")){
//Metano
dataToShow = "Metano";
}
}
return dataToShow;
}
I use the rawData.substring(7) because 3 is the characters that i tell at the start of post
10c
And the other 4 are
410c
So i get only the value that i need to decimal... but sometimes i get outof bound....
Someone have some idea to get this with no problems?
Thanks
Related
I have different screens for different entities which are Products, Rooms, Posts, and, Users.
All of them have distinct ID which I use to open the particular screen to try to load the data from the ID parameter passed on the relevant screen/activity via the APIs.
The mechanism I thought for Products,Rooms,and Posts in particular are that on Notifications Screen and alike, I want to send coded or tagged string; like below for Products for example:
You have bid on <p244 24LED Lampshade />
And to match the above I have a regular expression:
<p([0-9]*)\s(.*?)\/>(\s|$)
Here's a sample string:
String dummyText = "Hi #dan we product test <p1337 product />" +
"\n how about <r123 Room name/> is a nice room" +
"\n what <t234 this post details more about it/> but you should " +
"\n #poprocks woah one #sad";
It seems to work fine with single use of the product/post/room, but it messes up with more instances of the coded/tagged string.
But like I stated, with multiple instances like the following test:
String dummyText = "Hi #dan we product test <p1337 product /> and were more happy with <p53 car/> " +
"\n eh <r123 Room name/> is a nice room and <r233 dans house/> sucked while <r123 fun time/> was ok " +
// "\n what <t234 this post details more about it/> but you should " +
"\n <t234 view this as well/>" +
"\n #poprocks woah one #sad";
It messes up:
Here's my entire code process:
String dummyText = "Hi #dan we product test <p1337 product /> and were more happy with <p53 car/> " +
"\n eh <r123 Room name/> is a nice room and <r233 dans house/> sucked while <r123 fun time/> was ok " +
// "\n what <t234 this post details more about it/> but you should " +
"\n <t234 view this as well/>" +
"\n #poprocks woah one #sad";
List<Pattern> patternsList = new ArrayList<>();
patternsList.add(Pattern.compile(REGEX_NOTI_ROOMS)); //0
patternsList.add(Pattern.compile(REGEX_NOTI_PRODUCTS)); //1
patternsList.add(Pattern.compile(REGEX_NOTI_TWEETS)); //2
patternsList.add(Pattern.compile(REGEX_NOTI_MENTION)); //3
patternsList.add(Pattern.compile(REGEX_ARABIC_N_NUM_HASHTAG)); //4
holder.row_noti_messageTV.setText(makeSpannable(dummyText, patternsList));
holder.row_noti_messageTV.setMovementMethod(new PkMovementMethod());
Where the relevant regex are:
public static final String REGEX_NOTI_ROOMS ="<r([0-9]*)\\s(.*?)\\/>(\\s|$)";
public static final String REGEX_NOTI_PRODUCTS ="<p([0-9]*)\\s(.*?)\\/>(\\s|$)";
public static final String REGEX_NOTI_TWEETS ="<t([0-9]*)\\s(.*?)\\/>(\\s|$)";
public static final String REGEX_ARABIC_N_NUM_HASHTAG ="#(\\w*[0-9a-zA-Zء-ي٠-٩]+\\w*[0-9a-zA-Zء-ي٠-٩])";
public static final String REGEX_NOTI_MENTION ="(?:^|\\s|$|[.])#[\\p{L}0-9_]*";
And my makeSpannable method is:
public SpannableStringBuilder makeSpannable(String rawText, List<Pattern> listofPatterns) {
// StringBuffer sb = new StringBuffer();
SpannableStringBuilder spannable = new SpannableStringBuilder(rawText);
for(int i=0; i<listofPatterns.size(); i++)
{
Matcher matcher = null;
if(i==0) //init only
matcher = listofPatterns.get(i).matcher(rawText);
else
matcher = listofPatterns.get(i).matcher(spannable);
while (matcher.find()) {
showLogMessage("jsonParse", "hit on iteration" + i + " group == " + matcher.group());
if(i==3 || i == 4)
{
try {
String abbr = matcher.group();
showLogMessage("jsonParse", "loop[3 | 4 are normal] == " + i + " group(0) == " + abbr);
int start = matcher.start();
int end = matcher.end();
NotificationSpan ourSpan = new NotificationSpan(Color.BLUE, Color.RED, Color.TRANSPARENT, new IdTitleStore(abbr, abbr, abbr), NotificationAdapter.this);
spannable.setSpan(ourSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
e.printStackTrace();
}
}
else if(i<=2) {
try {
String orgGroup = matcher.group();
// get the match
String abbr = matcher.group(2);
showLogMessage("jsonParse", "loop == " + i + " group2 == " + abbr);
int startPoint = matcher.start();
int endPoint = matcher.end();
NotificationSpan ourSpan = new NotificationSpan(Color.RED, Color.BLUE, Color.TRANSPARENT, new IdTitleStore(matcher.group(1), abbr, orgGroup), NotificationAdapter.this);
Spannable spanText = new SpannableString(abbr);
spanText.setSpan(
ourSpan, 0, abbr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
spannable.replace(startPoint, endPoint, spanText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return spannable;
}
Note: NotificationSpan is a custom span I use to store the group(1) as it has the ID and from group(0) I can deduce on click whether it may be a Post, Product, or a Room entity to open it.
Any feedback shall be appreciated, even if it can point me towards the right direction. Like if my approach in itself is fundamentally wrong or something, please do let me know.
EDIT: Someone pointed out at comments to remove the redundant (\s|$) from the Regular Expressions, and it did seemingly nothing
Logs for the dummyString I tested:
String dummyText = "Hi #dan we product test <p1337 product /> and were more happy with <p53 car/> " +
"\n eh <r123 Room name/> is a nice room and <r233 dans house/> sucked while <r123 fun time/> was ok " +
"\n what <t233 this post details more about it/> but you should " +
"\n <t234 view this as well/>" +
"\n #poprocks woah one #sad";
E/jsonParse: hit on iteration0 group(0) == <r123 Room name/>
E/jsonParse: hit on iteration0 group(0) == <r233 dans house/>
E/jsonParse: hit on iteration0 group(0) == <r123 fun time/>
E/jsonParse: hit on iteration1 group(0) == <p1337 product />
E/jsonParse: hit on iteration1 group(0) == <p53 car/>
E/jsonParse: hit on iteration2 group(0) == <t234 view this as well/>
E/jsonParse: hit on iteration3 group(0) == #dan
E/jsonParse: hit on iteration4 group(0) == #poprocks
E/jsonParse: hit on iteration4 group(0) == #sad
It is also weird that the first instance is not detected by the matcher at all.
i.e
"\n what <t234 this post details more about it/> but you should "
It may entirely be possible that something is wrong with the logic itself of the Multiple Patterns being matched inside loops, but I really can't seem to figure it out. Appreciate the comment though!
EDIT EDIT*: I think I finally understand what the problem was/is. Adding dot after the replace method it gave me two suggestions, notify() and notifyAll(), which got me wondering this is indeed multi-thread based operation (sort of obvious to others but yeah!). So the multiple loop was in fact the issue.
Since replacing a call updates the span itself, the inner loop (while mathcer.find()) did not have the latest span on the matcher, it had different/previous one, which would've worked fine if there were only one instance found, but since in case of multiple the start and end were way off and hence some unintended stuff was happening. Followings the updated code, I did keep the (\s|$) just in case a Product/Post/Room is the end of the string so it does match and not remain blank.
public SpannableStringBuilder makeSpannable(String rawText, List<Pattern> listofPatterns) {
SpannableStringBuilder spannable = new SpannableStringBuilder(rawText);
Matcher matcher = null;
for(int i=0; i<listofPatterns.size(); i++)
{
matcher = listofPatterns.get(i).matcher(spannable.toString());
while (matcher.find()) {
showLogMessage("jsonParse", "hit on iteration" + i + " group == " + matcher.group());
if(i<=2) {
try {
String orgGroup = matcher.group();
// get the match
String abbr = matcher.group(2);
showLogMessage("jsonParse", "span txt of iteration " + i + " going to be group2 == " + abbr);
int startPoint = matcher.start();
int endPoint = matcher.end();
NotificationSpan ourSpan = new NotificationSpan(Color.RED, Color.BLUE, Color.TRANSPARENT, new IdTitleStore(matcher.group(1), abbr, orgGroup), NotificationAdapter.this);
Spannable spanText = new SpannableString(abbr);
spanText.setSpan(
ourSpan, 0, abbr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
);
spannable.replace(startPoint, endPoint-1, spanText);
matcher = listofPatterns.get(i).matcher(spannable);
} catch (Exception e) {
e.printStackTrace();
}
}
else {
try {
String abbr = matcher.group();
showLogMessage("jsonParse", "span txt of iteration " + i + " going to be group(0) == " + abbr);
int start = matcher.start();
int end = matcher.end();
NotificationSpan ourSpan = new NotificationSpan(Color.BLUE, Color.RED, Color.TRANSPARENT, new IdTitleStore(abbr, abbr, abbr), NotificationAdapter.this);
spannable.setSpan(ourSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return spannable;
}
Additional note: I think it'd be better if I explain why I've divided the loop into two parts to begin-with as well. The reason is simple, first 3 of my REGEX I 100% know for sure have group(2) elements, which I have implemented the click ID mechanism of. The last two are normal hashtag and mention ones which don't have group(2).
Here's the final working look, hope I don't face any performance issues:
I'm trying to concat multiple results which is generating separately. Already tried to put the results in a TextView but it only shows thw last result.
Log.wtf("Concat ", msg2);
E/Concat: A4 Paper 6 -> $ 57.0
E/Concat: JetPen 8 -> $ 105.0
E/Concat: Shopper 9 -> $ 110.25
E/Concat: Pilot 10 -> $ 70.0
E/Concat: Valentine Card 2 -> $ 60.0
List<Basket> items = ((BasketAdapter)binding.get().basketRecycler.getAdapter()).getItems();
for(Basket basket : items){
//Log.wtf("Name ", basket.product.name);
//Log.wtf("Price ", basket.basketPrice + "");
//Log.wtf("Count ", basket.count + "");
float subTotal = basket.basketPrice * basket.count;
String message = basket.product.name +" "+"->"+" "+" $ "+subTotal;
Log.wtf("Concat ", message);
Try this , your code is not working because you are creating new string every time inside of for loop. What I have done is created a variable message outside for loop and concatinated it inside loop using += operator
List<Basket> items =
((BasketAdapter)binding.get().basketRecycler.getAdapter()).getItems();
String message = "";
for(Basket basket : items){
//Log.wtf("Name ", basket.product.name);
//Log.wtf("Price ", basket.basketPrice + "");
//Log.wtf("Count ", basket.count + "");
float subTotal = basket.basketPrice * basket.count;
message += basket.product.name +" "+"->"+" "+" $ "+subTotal;
Log.wtf("Concat ", message);
You are declaring String message in for loop. Thats why each time new object is created. Declare String message outside of for loop.
I am getting json data from server like this -
if (response->isSucceed()) {
log("Get success");
std::vector<char>* buffer = response->getResponseData();
std::string res;
res.insert(res.begin(), buffer->begin(), buffer->end());
log("res: %s", res.c_str());
rapidjson::Document d;
d.Parse<0>(res.c_str());
if(d.IsObject()){
log("true"); // print the value of obtaining hello
}
F = d["F"].GetString();
W = d["W"].GetString();
T = d["T"].GetString();
Fp = d["Fp"].GetString();
Wp = d["Wp"].GetString();
Tp = d["Tp"].GetString();
}
Now i want to display that value of “F” using label…Value of F is integer number.
So i do this -
foodnumber = Label::createWithTTF(F, "fonts/A little sunshine.ttf", 40 );
foodnumber->setColor(Color3B(109,61,23));
foodnumber->setPosition( Vec2(foodtitle->getPositionX() + foodtitle-
>getContentSize().width/4 + origin.x, foodtitle->getPositionY() + origin.y)
);
this->addChild( foodnumber);
It doesn’t print the value…
The value in the F is Number.
But when i log the value, it gets logged right, but it doesn’t get displayed on app as label.
Thank you
When we want to get minor and major with this code we get null in both , but in log we get the values :
when we want to get minor and major with this code we get null in both , but in log we get the values :
Beacon firstBeacon = beacons.iterator().next();
Log.i(TAG,"The first beacon " + firstBeacon.toString() + " is about " + firstBeacon.getDistance() + " meters away.");
Log.i(TAG, "The first beacon I see has minor id "+beacons.iterator().next().getId3());
Log.i(TAG, "The first beacon I see has major id "+beacons.iterator().next().getId2());
String minor = beacons.iterator().next().getId3();
String major = beacons.iterator().next().getId2();
You can try
ArrayList<Beacon> mylist = new ArrayList<Beacon>(beacons);
for (int j = 0; j < mylist.size(); j++) {
String rangedUUID = mylist.get(j).getId1().toString();
String rangedMajor = mylist.get(j).getId2().toString();
String rangedMinor = mylist.get(j).getId3().toString();
}
or you can replace this
String minor = beacons.iterator().next().getId3();
String major = beacons.iterator().next().getId2();
with
String minor = firstBeacon.getId3();
String major = firstBeacon.getId2();
Because
beacons.iterator().next()
give next beacon
I'm developing an app where I need to send 3 seekbar's values to a PCB via bluetooth. I've done all the bluetooth code based on the bluetoothchat example. I first modified it to send a string with these 3 values. But now, I need to do something more dificult and i don't know how to do it.
First of all, in the app i modify the seekbars and then i click on the send button. In the code, I need to set a string for each seekbar's value, because I need to access to the MCU variables and set each variable address, value, CRC etc...
So, I need to know the correct way to do this. Here is the code where i define the send function:
/**
* SEND THREAD
*/
/**[Start Thread + Send command + Nº bytes thread + Nº bytes variable + Address + Variable value + CRC]*/
public void sendValues() {
/**Set the seekbars values into a string*/
send_value1 = Integer.toString(savedProgress1);
send_value2 = Integer.toString(savedProgress2);
send_value3 = Integer.toString(savedProgress3);
String message1 = start_thread+" "+send_command+" "+num_byte_trama1+ " "+num_byte_variable+" "+pos_reg_1+" "+Value+" "+CRC;
String message2 = start_thread+" "+send_command+" "+num_byte_trama1+ " "+num_byte_variable+" "+pos_reg_2+" "+Value+" "+CRC;
String message3 = start_thread+" "+send_command+" "+num_byte_trama1+ " "+num_byte_variable+" "+pos_reg_3+" "+Value+" "+CRC;
String message4 = start_thread+" "+send_command+" "+num_byte_trama2+ " "+num_byte_variable+" "+pos_reg_save_request+" "+Value+" "+CRC;
String message5 = start_thread+" "+send_command+" "+num_byte_trama2+ " "+num_byte_variable+" "+pos_reg_save_status+" "+Value+" "+CRC;
/**Check that we're actually connected before trying anything*/
if (GlobalVar.mTransmission.getState() != GlobalVar.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
/**Get the message bytes and tell the Transmission to write*/
byte[] send = message.getBytes();
GlobalVar.mTransmission.write(send);
/**Reset out string buffer to zero*/
GlobalVar.mOutStringBuffer.setLength(0);
}
There are these few things that I ask you to help me:
1- Need to know how to calculate the CRC
2- I need to send these 5 strings together when pressing the send button.
In the part where i get the bytes to send, I don't know If the right way to do this would be to add these 5 strings on 1 and send this one (maybe it would be to long if I do this), or to create a function to send these 5 separately but at the same time.
This is the edited code to send each message one by one:
/**Conversion to decimal of the seekbar's % value*/
send_int1 = ((savedProgress1 * 20480) / 100) * -1;
send_int2 = ((savedProgress2 * 20480) / 100) * -1;
send_int3 = ((savedProgress3 * 20480) / 100) * -1;
/**Conversion to string of the previous values to send in the string message*/
sendValue1 = Integer.toString(send_int1);
sendValue2 = Integer.toString(send_int1);
sendValue3 = Integer.toString(send_int1);
String message1 = start_thread+" "+send_command+" "+num_byte_trama1+" "+num_byte_variable+" "+pos_reg_1+" "+sendValue1+" " ;
String message2 = start_thread+" "+send_command+" "+num_byte_trama1+" "+num_byte_variable+" "+pos_reg_2+" "+sendValue2+" " ;
String message3 = start_thread+" "+send_command+" "+num_byte_trama1+" "+num_byte_variable+" "+pos_reg_3+" "+sendValue3+" " ;
String message4 = start_thread+" "+send_command+" "+num_byte_trama2+" "+num_byte_variable+" "+pos_reg_save_request+" " ;
String message5 = start_thread+" "+send_command+" "+num_byte_trama2+" "+num_byte_variable+" "+pos_reg_save_status+" " ;
/**Check that we're actually connected before trying anything*/
if (GlobalVar.mTransmission.getState() != GlobalVar.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
/**Get the message bytes and tell the Transmission to write*/
byte[] send1 = message1.getBytes();
GlobalVar.mTransmission.write(send1);
//Wait untill I receive the confirmation from the MCU
byte[] send2 = message2.getBytes();
GlobalVar.mTransmission.write(send2);
byte[] send3 = message3.getBytes();
GlobalVar.mTransmission.write(send3);
byte[] send4 = message4.getBytes();
GlobalVar.mTransmission.write(send4);
byte[] send5 = message5.getBytes();
GlobalVar.mTransmission.write(send5);
/**Reset out string buffer to zero*/
GlobalVar.mOutStringBuffer.setLength(0);
}
For your frame, I recommand you to use this kind of frame :
final byte[] HEADER = AA11 // For example
// When you want to send a message :
Strign messageToSend = new String(HEADER) + yourStringMessage
It'll be easier for you to analyze the frame when you receive it.
Then, for the CRC, I can't answer if you don't tell the kind of CRC. In my app, I used
private static char createCRC(byte[] frame)
{
int crc = 0;
for(byte i : frame)
{
crc = crc^i;
}
return (char)crc;
}
to create the CRC by "XORing" each byte of my message , and then check a CRC is quite easy
UPDATE : Well, I finally get it.
In the BluetoothChat activity, you get a string version of message, and the byte[] one.
If you want to get the first byte of the message, just add byte myByte = readBuf[0] before String readMessage = new String(readBuf, 0, msg.arg1);
Then, String readMessage = new String(myByte, 0, msg.arg1);