Reputation: 5984
I am connecting to a terminal emulator using a library in android, this connects to a serial device (a switch) and shows me sent/received data.
However I am just sending byte arrays over and back so I don't know what status the switch is in, is it in enable more or configuration mode etc. This leads me to possibly enter commands in the wrong mode and they won't work. The switch is then in an unrecoverable mode as I have sent a wrong command and there is no way to delete it or get to a new line. The problem I am trying to deal with for now is the one where I don;t know the mode the switch is in. I know that I can have three different return prompts after I send a command:
switch>
switch#
switch(config)#
So I was thinking that if I read the last two characters received I could tell which mode I'm in. h>, h# and )#
I get data back in this method, whenever data is received this is run:
public void onDataReceived(int id, byte[] data)
{
String str = new String(data);
((MyBAIsWrapper) bis).renew(data);
mSession.write(str);
mSession.notifyUpdate();
viewHandler.post(updateView);
}
Would the best way to do this be search the byte array somehow or to convert it to a string and search the string for h>, h# and )#, then I could set a global variable depending on the value I get back? Maybe search from the end backwards?
Upvotes: 1
Views: 5923
Reputation: 10161
I would search the byte[]
and avoid the overhead from the conversion to a String
.
If it is more performant to start search from the end, depends on the data you get. I cannot judge this by the little example you posted in your question.
If you only need to look at the last two characters:
if(data[data.length-2]=='h' && data[data.length-1]=='>') // "h>"
if(data[data.length-2]=='h' && data[data.length-1]=='#') // "h#"
Or if it is not so simple, use a loop to iterate the array.
P.s. I assumes ASCII encoding for the code above
Upvotes: 4
Reputation: 533790
Do you mean?
if(str.endsWith("h>") || str.endsWith("h#") || str.endsWith(")#"))
or simpler
if(str.equals("switch>") || str.equals("switch#") || str.equals("switch(context)#"))
or using a regex
final Pattern switched = Pattern.compile("switch(>|#|\\(\\w+\\)#)");
if(str.matcher(switched).matches())
Upvotes: 2