My code receive data on my Android phone from Arduino via USB host.
The data (in form of bytes) is transformed to String Output, I write code in the method updateReceivedData(byte[]) that checks if the data contains "Warning" word, to send message containing the warning data
I try to make counter to make delay between sending messages in case of continuous warning received data, then I would to reset the counter if there is no warning message
My problem is that the counter reset every time and continue sending message without making delay.
I think the solution is by making delay while The String output is completed, then check on it, but I don't know how?
private void updateReceivedData(byte[] data) throws UnsupportedEncodingException {
String Output = new String(data);
if(Output.contains("Warning")){
if (warncounter==0){
Toast.makeText(getBaseContext(), "Warning message sent", Toast.LENGTH_SHORT).show();
SmsManager.getDefault().sendTextMessage(number, null, Output, null, null);
}
warncounter++;
if(warncounter==52) warncounter=0;
}
else warncounter=0;
mDumpTextView.append(Output);
mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}
To make an approach for finding the problem, I try this code
private void updateReceivedData(byte[] data) throws UnsupportedEncodingException {
String Output = new String(data);
if(Output.contains("Warning")){
SmsManager.getDefault().sendTextMessage(number, null, Output, null, null);
}
}
mDumpTextView.append(Output);
mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
}
In the second code, I let all received data contain warning, the result is that the first message contains the whole output string, but after the first, all received messages are trimmed (maybe due to the data was not completely transformed to string before start sending string)
Note: The data are sent from Arduino every one second, and the data in the scrollview text appears correctly 100% (this indicates that the data was transformed to String but maybe the problem is that it takes time)
So please help or make suggestions
I found the problem
The problem is that android cannot read the whole data sent from arduino (using Serial.print ()) by a single bulktransfer () function call, so I make the bulktransfer () (or read) in a while loop, then I check on each Sting sent by arduino by building a String when each new line ("\n") is detected in the readed data
Related
So I came across something strange that made me loose some time. I have been trying to print the content of an ArrayList containing string elements, sometimes, an element might contain an empty string, which is fine and absolutely my intention.
So I have something like this:
List<String> l = new ArrayList<String>();
//adding strings in l, sometimes it's an empty string
for (int i=0; i < l.size(); i++) {
Log.w("element in l : ", l.get(i));
}
So here, when the loop is gonna hit the empty string, logcat is simply NOT going to print it out BUT (and here is the root of my confusion), if you have a message following the one that failed to display, suddenly the failed message is going to show up as if it contained the new logcat message. For example if you try logging an empty string like this
Log.w(TAG, <empty string here>);
Logcat is going to output nothing at first, then, when it has a NEW message to display this is what it prints out (in this case the new message is some warning about AudioTrack):
08-21 17:06:02.265 13047-13047/company.myapp W/TAG﹕ [ 08-21 17:06:05.411 766: 937 W/AudioTrack ]
AUDIO_OUTPUT_FLAG_FAST denied by client
I'm interested in knowing how this happens, maybe it can help someone else not getting super confused like I did. I suppose trying to log an empty string triggers some kind of buffer that sits there until it gets something to print, is this a bug?
That is an interesting question. I just tried this in LogRabbit and am able to see the same result.
I took a quick browse through the android source and see that Log.W(...) ends up in native code and getting handled in logd_write.c
This basically writes the data to /dev/log/main (or one of the other logs)
You can get those logs like this:
adb pull /dev/log/events .
adb pull /dev/log/main .
adb pull /dev/log/radio .
adb pull /dev/log/system .
You will need to press cntl-C otherwise the copy will happen forever.
Looking in the raw log in /dev/log/main I see the message does get logged:
<8b>F×U^_<8c>^Y^U^Emfl_MessageList^#Before Empty^#^R^#^#^#!z^#^#!z^#^#
<8b>F×U^_<8c>^Y^U^Emfl_MessageList^#^#^]^#^#^#!z^#^#!z^#^#
<8b>F×U^_ <8c>^Y^U^Emfl_MessageList^#After Empty^#7^#^#^#^#^E^#^#^Z^E^#^#
That gets decoded by struct found in logger.h So I think this is a problem in adb. pull the source code from here: (looks like quite a few of undocumented commands there)
This is the primary function
static int logcat(TransportType transport, const char* serial, int argc, const char** argv) {
char* log_tags = getenv("ANDROID_LOG_TAGS");
std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
std::string cmd = "shell:export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
if (!strcmp(argv[0], "longcat")) {
cmd += " -v long";
}
--argc;
++argv;
while (argc-- > 0) {
cmd += " " + escape_arg(*argv++);
}
return send_shell_command(transport, serial, cmd);
}
Looking in there I see that all logcat does is basically this:
adb shell
> exec logcat
So I think the root of the problem is in logcat itself. Logcat.cpp calls into log_read.c
Based on my quick read through things what I think is happening is the message is not terminated properly. The empty message does not show up until another message is appended and the first message overruns and shows the second message because it has the appropriate termination.
I have called navision web service succesfully by authenticating it through the use of NTML authentication protocol. And i also got the full, Proper data for all the Method but i have issue in calling READ MULTIPLE METHOD with Filter. i have passed filter in below manner.
CustomerList_Filter customFilter = new CustomerList_Filter();
customFilter.field = CustomerList_Fields.Name;
customFilter.criteria = "B*";
VectorCustomerList_Filter vfilter = new VectorCustomerList_Filter();
vfilter.add(customFilter);
custService.ReadMultipleAsync(vfilter, null,0);
Eventhough i passes Filter to get Customer name Record starting with B letter still it shows all customer. & custService is an object of CustomerList_Service class.Please help.
It is said that first parameter of ReadMultiple is array. Is VectorCustomerList_Filter an array? Maybe you should write custService.ReadMultipleAsync(vfilter.ToArray(), null,0);
Also you can try to put code the way in this answer. salesOrdersService.ReadMultiple(new SalesOrders_Filter[] { filter }, null, 0);
If this not helps then try to catch output XML message that is sent as request to web service. You'll be able to find error by analyzing it.
I am learning to use zeromq polling in android . I am polling on a req socket and a sub socket in the android program(client). So that this client can receive both reply messages from the server and also published messages.
My polling is not working. Both the req socket and the publish socket does not get polled in. If i don't use polling both the sockets receive the message.
I tried searching online but could not find anything relevant.
The client code is this :
public void run()
{
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket reqsocket = context.socket(ZMQ.REQ);
ZMQ.Socket subsocket =context.socket(ZMQ.SUB);
reqsocket.connect("tcp://10.186.3.174:8081");
subsocket.connect("tcp://10.186.3.174:8083");
subsocket.subscribe("".getBytes());
byte[] receivedmessage;
Poller poller=context.poller();
poller.register(reqsocket,Poller.POLLIN);
poller.register(subsocket,Poller.POLLIN);
reqsocket.send(msg.getBytes(),0);
while(!Thread.currentThread().isInterrupted())
{
if(poller.pollin(0))
{
receivedmessage=s.recv(0);
}
if(poller.pollin(0))
{
receivedmessage=subsocket.recv(0);
}
}
s.close();
context.term();
}
Am i missing out something or doing something wrong?
It looks like there are 3 problems with this.
The main one is you need to call poller.poll() as the first thing inside the while loop. This is why you are not getting any messages.
The next issue is that you're checking the same index for both sockets: I expect the second if statement needs to be
if(poller.pollin(1))
Lastly, the req socket requires a send before every receive, so the call to send needs to be inside the while loop, and before the poller.poll() you just added above :)
I opened a socket between an Android app and a python server. The combination is that the Server listens, and android connects to the Server.
Here is the server code. The problematic part takes place in the definition of handle :
import SocketServer
from time import sleep
import sys
HOST = '192.168.56.1'
PORT = 2000
class SingleTCPHandler(SocketServer.StreamRequestHandler):
def handle(self):
try:
while(1):
sleep(0.03)
data = self.rfile.readline().strip()
print data
except KeyboardInterrupt:
sys.exit(0)
class SimpleServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
allow_reuse_address = True
def __init__(self, server_address, RequestHandlerClass):
SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass)
server = SimpleServer((HOST, PORT), SingleTCPHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
sys.exit(0)
The connection is established normally, and the Android app sends the following data to the socket:
'0:0'
But the data is received on the Server as:
'\x000\x00:\x000\x00'
The variable that receives the data is:
data = self.rfile.readline().strip()
and printing gives the regular format:
In [2]: print data
0:0
I didn't manage to step into the print function with pdb to see what it does.
I'm looking for a way to convert the '\x000\x00:\x000\x00' to '0:0'.
Please advise on a way to convert the variable. You are welcome to comment/criticize the whole implementation. This is my first project in dealing with sockets so i don't know the pitfalls.
Update
This was the original Android code:
String podaci = "0:0";
public void Socketic() throws IOException {
Socket mojSocket = new Socket(urlServer, port);
DataOutputStream izlazdata = new DataOutputStream(
mojSocket.getOutputStream());
while (podaci != "end") {
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
izlazdata.writeChars(podaci);
izlazdata.flush();
}
izlazdata.close();
mojSocket.close();
};
And the problem was, as you suspected in:
izlazdata.writeChars(podaci);
writeChars uses the method writeChar. The API documentation for writeChar states:
Writes a char to the underlying output stream as a 2-byte value, high byte first...
The two bytes represent the 16bits which UTF-16 uses for encoding.
When we changed it to everything started working:
izlazdata.writeBytes(podaci);
Update
Based on the answers given, here is how the unwanted string is to be interpreted in terms of characters.
This solves my concrete problem, however, if someone would give a more generic solution to what happend here so that a larger lesson can be learned.
If not, i will accept Esailijas answer in a few days.
You need to show the code happening Android but it strongly seems like it's sending data in UTF-16BE. You should specify the encoding on the Android end. The characters are not hexadecimal literally, but because the NUL character is unprintable, python shows \x00 instead.
Another option is to decode it:
self.rfile.readline().decode("utf_16_be").strip()
note that the result of this is an unicode string.
I'm writing an Android application that allows a call and response between two devices. I'm currently using sendMultipartTextMessage to send a message longer than 160 characters. However the message received is not the message I sent.
String response = "abcd abcd abcd abcdabcd abcd abcd abcd abcd...to 300 chars";
Log.i("response",response);
SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(response);
for (String part : parts) {
Log.i("part",part);
}
sms.sendTextMessage(sender, null, "This should be normal", null, null);
sms.sendMultipartTextMessage(sender, null, parts, null, null);
The Log.i runs as expected and outputs the message in parts. The sendTextMessage also sends the correct SMS to my partner emulator. However, the parts sent by sendMultipartTextMessage all come back oddly translated. For example the above response would be received as "BEGIABEGIABEGIABEGIA..." and so on with a few minor variations for spaces and numbers.
What is causing sendMultipartTextMessage to garble the SMS?
Its a bug in the platform: see http://code.google.com/p/android/issues/detail?id=13737. It might be limited to the simulator, so try it on a real device.
sendMultipartTextMessage method does not work correctly when you run your android application from any simulator.
so you need to test your android application on actual android smart phone. one more thing to consider is always pass null as third second argument (string containing phone number of sender) while sending SMS otherwise code will not sms.
i hope this will help you.