Complete CONNECTIVITY_SERVICE test - java

My application connects to the internet onCreate, it does this in an AsyncTaks class and all works fine. I have some error checking in place to make sure there is internet available and works great if I say put my phone on Flight Mode.
My problem is when I’m on WIFI, where I live the WWW drops out from time to time but the phone still thinks it’s connected. E.g.. the phone is still connected to the WIFI dongle but the WIFI dongle is not connected to the WWW, so when the application opens and tries to connect it gets an error and I get a force close.
How can I do a complete internet connection check onCreate that will cover all bases???
Cheers,
Mike.

One possibility is just to handle the error that you are getting in a better manner. You are getting a force close right now because (I assume) you are getting a RuntimeException from your application. Handling the exceptions and putting up proper messaging to your user might be adequate.
Another way is just make one (or a couple) connections to some high available servers to see if it works. For example, something like the following should work:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.google.com/");
try {
HttpResponse response = client.execute(request);
txtResult.setText(HttpHelper.request(response));
// internet is working
} catch(Exception ex) {
// internet is not working
txtResult.setText("Internet ENOWORK");
}
If you post the exception/error that you are getting and comment on my answer I can edit it with more specifics.

Related

BMP280 ServiceSpecificException: I/O error (code 5)

I try to use AndroidThings to measure temperature with Raspberry Pi 3 and BMP280.
3,3V i have choosed because of specification of BMP280:
To power the board, give it the same power as the logic level of your microcontroller
Then i want to initialize sensor
mTemperatureSensorDriver = new Bmx280SensorDriver("I2C1");
And by execution i receive following exeption
Error configuring sensor
com.google.android.things.pio.PioException: android.os.ServiceSpecificException: I/O error (code 5)
at com.google.android.things.pio.I2cDeviceImpl.readRegByte(I2cDeviceImpl.java:81)
at com.google.android.things.contrib.driver.bmx280.Bmx280.connect(Bmx280.java:215)
at com.google.android.things.contrib.driver.bmx280.Bmx280.<init>(Bmx280.java:193)
at com.google.android.things.contrib.driver.bmx280.Bmx280.<init>(Bmx280.java:180)
at com.google.android.things.contrib.driver.bmx280.Bmx280SensorDriver.<init>(Bmx280SensorDriver.java:55)
Also by 5V Power i receive the same exception.
I have found this. But i have no idea how to check, if the BMP280 is realy connected to Raspberry with adb.
By own testing the connectivity i receive by device.readRegByte(0xD0) the same exeption.
Does it mean, that BMP280 is not correctly connected?
If yes, how to correctly connect BMP280 with Raspberry?
Is some resistor needed by connection?
UPDATE
solved by soldering BMP280 with header strip.
Also to work with sensor is permission requiered that could be granded only in command line. ref
adb shell pm grant app.package com.google.android.things.permission.MANAGE_SENSOR_DRIVERS
Looking at your fritzing diagram you had SDO connected to BCM3?
From the datasheet the SDO pin is what determins the address of your sensor.
Connecting SDO to GND results in slave
address 1110110 (0x76); connection it to VDDIO results in slave address 1110111 (0x77)
Most importantly:
The SDO pin cannot be left floating; if left floating, the
I²C address will be undefined.
com.google.android.things.pio.PioException: android.os.ServiceSpecificException: I/O error (code 5)
Therefore your problem is likely an undefined i2c address.
Looking at the code you are using for the Bmx280SensorDriver, it uses the address 0x77
https://github.com/androidthings/contrib-drivers/blob/master/bmx280/src/main/java/com/google/android/things/contrib/driver/bmx280/Bmx280.java#L48
Therefore you should ensure your SDO line is connected to 5V on your raspberry pi. This will ensure your sensor has the correct address.
Or alternatively connect SDO to Ground and use this constructor:
mTemperatureSensorDriver = new Bmx280SensorDriver("I2C1", 0x76);
If you want to understand what the sensor driver is doing "under the hood" there is a great blog post and repo to see that:
http://blog.blundellapps.co.uk/tut-android-things-temperature-sensor-i2c-on-the-rainbow-hat/
https://github.com/blundell/androidthings-i2c-input/blob/master/app/src/main/java/com/blundell/tut/MainActivity.java
;-)
Thanks for informations, for right connection
bmx280 = new Bmx280("I2C1",0x76); and SDO to gnd.
But read values is strange.
myweatherstation D/statie: temp: 186.83298 pres: -296.47287
Is possible to be sensor damaged?
TNX
Cris
To read data from IoT Device, the contact should be fixed without any loose connection.
This could be only reached with soldering of BMP280 with header strip
Only then the connection could be etablished

How to handle (failed) login attempts with Smack XMPP API

I'm developing a chat server based on XMPP and Smack API, which connects to an Openfire server (Hosted by a friend who is also developing this with me).
So, I started programming it just a few days ago (Netbeans on OS X 10.8), and today I went on to the connection and login aspects.
I can login perfectly with the right choice of username+password :P but I don't know how to handle an invalid login attempt and let the app show a message and then allowing the user to retry.
Here's my code, which fires after user has pressed a button in my Swing JForm:
(Note: XMPPConnection object is already created in another class, and the connection has been made to the server. You can see I'm calling the object from that another class)
private void btnIniciarSesionActionPerformed(java.awt.event.ActionEvent evt) {
String Usuario = txtUsuario.getText();
String Password = new String (pwdContrasena.getPassword());
if (Usuario.equals("") || Password.equals("")){
// Missing data
JOptionPane.showMessageDialog(null, "Missing data");
}
else{
//Try to login
try{
Proyecto_chat.conexion.login(Usuario, Password, "x");
}
catch (XMPPException ex){
Logger.getLogger(Ventana_login.class.getName()).log(Level.SEVERE, null, ex);
// Problem
}
if (Proyecto_chat.conexion.isAuthenticated() == true){ //Login has been successful
jLabel1.setVisible(false);
System.out.println("Authenticated as " + Usuario);
JOptionPane.showMessageDialog(null, "Authenticated as " + Usuario);
//Exit login window and carry on
}
else{
JOptionPane.showMessageDialog(null, "login error");
}
}
}
Should I play with that exception I'm getting? ->
SEVERE: null
SASL authentication DIGEST-MD5 failed: not-authorized:
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:337)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:203)
at proyecto_chat.Ventana_login.btnIniciarSesionActionPerformed(Ventana_login.java:159)
at proyecto_chat.Ventana_login.access$100(Ventana_login.java:15)
at proyecto_chat.Ventana_login$2.actionPerformed(Ventana_login.java:73)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
(...) more lines that I think are not critical for this
As passwords are stored in plain text (University project, so it doesn't matter) for simplifying changing them from inside the application, I can connect to the database (PostgreSQL in remote server) from the client computer, and check the passwords and only do 'conexion.login' if user&pass matches, but that would be... you know... wrong
After looking around on the web with no luck, I decided to head over here, ask, go to sleep and wake up next morning with some suggestions ;)
Help shall be appreciated
Not sure if I understand what you are asking but if it's "How can I determine the reason for a failed login attempt with Smack?" then here is my answer:
You have to evaluate the (XMPP)Exception's message string as of Smack 3.2.2 if you want to determine the reason for the failed login. These message strings that distinguish between the various failure reasons are currently hard-coded in the source, which is usually not a good idea.
A while ago I have created SMACK-416 "Improve Exceptions on connect() and login()" to address this issue. The idea is to replace the hard-coded strings/failure reasons with a class hierarchy. But it sure will take a few months until this is implemented (and maybe a few weeks/months/years until it is released).
Actually, the main problem was that when I tried to login using an invalid username/password, some exception was thrown (As well as an information display that I set up), but the application wouldn't let me log in again (As if I corrected my data and clicked the button again).
I finally solved this by placing the .connect() right behind the .login() method, and calling .disconnect() in case a bad login was made, so the server would be reconnected every time the user tried to log in .
This might not be the ideal approach, but I find it easy and do-able. Thanks for helping!

Can I globally set the timeout of HTTP connections?

I have a program that uses javax.xml.ws.Service to call a remote service defined by a WSDL. This program runs on the Google App Engine which, by default, sets the HTTP connection timeout to 5 seconds{1}. I need to increase this timeout value since this service often takes a long time to respond, but since this request is not being made with URLConnection, I cannot figure out how to call URLConnection.setReadTimeout(int){2}, or otherwise change the timeout.
Is there any way to globally set the HTTP connection timeout on the App Engine? And, for purposes of sharing knowledge, how would one go about solving this sort of problem generally?
{1}: https://developers.google.com/appengine/docs/java/urlfetch/overview#Requests
{2}: http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLConnection.html#setReadTimeout(int)
You could try setting the sun.net.client.defaultConnectTimeout and sun.net.client.defaultReadTimeout system properties documented here, e.g.
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
EDIT
Sorry, just re-read and noticed this is on Google App Engine. I don't know for sure, but given the litigious relationship Google and Oracle have lately, I'm guessing GAE doesn't run the Oracle JVM. I'll leave this here in case someone else runs into a similar problem.
Try this:
Port port = service.getPort(endPointInterface); //or another "getPort(...)"
((BindingProvider) port).getRequestContext()
.put(BindingProviderProperties.REQUEST_TIMEOUT, 30);
See https://developers.google.com/appengine/docs/java/urlfetch/usingjavanet
You can do something like this to get a URLConnection:
URL url = new URL("http://www.example.com/atom.xml");
URLConnection tempConnection = url.openConnection();
tempConnection.setReadTimeout(10);
For App Engine with JAX-WS you have to set the request context (tested today with SDK 1.9.15). For normal machines you cannot go higher than 60s and would have to switch to the bigger machines (Bx) for better use a task queue.
For local testing you would normally use BindingProviderProperties.CONNECT_TIMEOUT and BindingProviderProperties.REQUEST_TIMEOUT, but they are not on the App Engine JRE White List and your code inspection might constantly warn you about that.
The equivalent strings can be used though:
com.sun.xml.internal.ws.connect.timeout
com.sun.xml.internal.ws.connect.timeout
For deployment to App Engine:
com.sun.xml.ws.connect.timeout
com.sun.xml.ws.request.timeout
A full example how to apply that to auto-generated code from JAX-WS 2.x, values have to be provided in milliseconds:
#WebEndpoint(name = "Your.RandomServicePort")
public YourServiceInterface getYourRandomServicePort() {
YourRandomServiceInterface port = super.getPort(YOURRANDOMSERVICE_QNAME_PORT, YourRandomServiceInterface.class);
Map<String, Object> requestContext = ((BindingProvider)port).getRequestContext();
requestContext.put("com.sun.xml.ws.connect.timeout", 10000);
requestContext.put("com.sun.xml.ws.request.timeout", 10000);
return port;
}

Twiiter4J getDirectMessages() does not work anymore?

I am using Twitter4J 2.2.5 (latest, tried other versions). And can no longer get direct messages to work at all. The same code used to work a while ago. I assume Twitter changed something.
I'm using
Twitter.getDirectMessages()
and it gives the error below. No idea why, I can see the direct messages for the account if I login, but always get this error. The limit error makes no sense, as the account is no where near the limit.
Other API work, like followers/fried/status/etc.
403:The request is understood, but it has been refused. An accompanying error message will explain why. This code is used when requests are being denied due to update limits (http://support.twitter.com/forums/10711/entries/15364).
Relevant discussions can be on the Internet at:
http://www.google.co.jp/search?q=00919618 or
http://www.google.co.jp/search?q=332bf6ca
TwitterException{exceptionCode=[00919618-332bf6ca], statusCode=403, retryAfter=0, rateLimitStatus=RateLimitStatusJSONImpl{remainingHits=107, hourlyLimit=350, resetTimeInSeconds=1328297, secondsUntilReset=1116, resetTime=Fri Feb 03 14:39:45 EST 2012}, version=2.2.2}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:189)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:93)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1721)
at twitter4j.TwitterImpl.getDirectMessages(TwitterImpl.java:874)
at org.pandora.sense.twitter.TwitterDirectMessaging.checkDirectMessages(TwitterDirectMessaging.java:44)
at org.pandora.sense.twitter.TwitterDirectMessaging.checkProfile(TwitterDirectMessaging.java:35)
at org.pandora.sense.twitter.Twitter$1.run(Twitter.java:100)
at java.lang.Thread.run(Thread.java:662)
Twitter has some time ago changed the rules for direct messages. An app must be especially authorized by the user to access the direct messages.
Did you make sure this is true for you? You may go to the twitter web site and check for the app.
To get the direct message you should try the below code.It works for me.
getDirectMessages(); gives list of direct messages. We need to put for loop to get text of each message.
List<DirectMessage> messages = twitter.getDirectMessages();
for (DirectMessage message : messages)
{
System.out.println(message.getText());
}
Let me know if you get any error.

Reconnect to a device after device crashed

I have the following problem with the libusb-java and some self-made devices.
It could happen that such a device disconnects from the USB Port because it drains to much power (as an example: i have a USB-LED Light which needs sometimes more than 500mA).
In this case the USB Controller will reset the device and the device will startup normaly again.
Now i cant really detect such a problem except for trying to reinit the device on every Exception. But thats not working...
On Every Exception i call my init Method again, which looks like this:
private void initDevice() {
USB.init();
this.dev = USB.getDevice(idVendor, idProduct);
}
The Problem with that is, this runs without any problem, but the i get this error message when i want to send new data:
LibusbJava.controlMsg: error sending control message: Protocol error
How do i can reinit the device? Do i have to reset the bus or something?
You will need to call open() on the device - it is new for the system.

Categories

Resources