I use this code
luugiathuy.com/2011/02/android-java-bluetooth/
The server side is the PC
the client is the device, with the app based on bluetooth chat example
The device (galaxy tab 7.0) can establish connection with the PC.
However the PC server (written in java and bluecove) did nothing, as nothing is connected.
The loop for trying to find connected device is
while(true) {
try {
System.out.println("waiting for connection...");
connection = notifier.acceptAndOpen();
Thread processThread = new Thread(new ProcessConnectionThread(connection));
processThread.start();
} catch (Exception e) {
e.printStackTrace();
return;
}
Output on PC:
uuid: 0000110100001000800000805f9b34fb
waiting for connection...
EDIT: source downloadhttps://github.com/luugiathuy/Remote-Bluetooth-Android
Same issue I got when I was trying in linux. But the reason (still not sure) when you run the bluetooth android application without turning on the Java server using bluecove, It will try to connect with the already installed bluetooth software. You may see the bluetooth icon asking for granting access to the mobile device.
To solve this, I just changed the uuid in the server and application (say from 1103 to 1101 and vice versa) and then started the server first and then the android application. Java server part started listening.
The reason I think may be the uuid when it did not found the bluecove stack service server, it got connected to the device server listening on same uuid. So after changing the uuid and making sure that the server is running before launching the android application should solve the issue.
If you are getting connected to the bluetooth system application and not to the Java bluecove server,
1) First change the uuid both server and android application.
2) Second make sure your server is running and listening on same uuid.
3) Launch the android application which try to communicate on same rfcomm connection uuid.
Server part code I took from : http://www.jsr82.com/jsr-82-sample-spp-server-and-client/
Library : http://code.google.com/p/bluecove/downloads/list
Yes, it happens with me too, I suggest you to fire following commend on shell, when it shows waiting for connection.
hcitool cc 58:C3:8B:D7:FA:F4
here 58:C3:8B:D7:FA:F4 is my device's bluetooth address, which should be replaced by your device's bluetooth address.
To get your device's bluetooth address, just start bluetooth in your device with discoverable mode and execute hcitool scan command, it will display all the active device with their name and bluetooth address.
Well you may run the above hcitool cc 58:C3:8B:D7:FA:F4 command via Java code as follows,
try
{
Process p=Runtime.getRuntime().exec("hcitool cc 58:C3:8B:D7:FA:F4");
}
catch ( Exception e )
{
}
The output from your program says it listens on UUID 0x1101. Is that true? The sample you reference shows it listening on a different UUID. Its Service Class Id is 0x04c6093b and is set as follows:
34 UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
35 String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
36 notifier = (StreamConnectionNotifier)Connector.open(url);
The two need to match on client and server.
Related
I built a flutter app which communicates with a web server that I wrote with flask. Everything works as intended without any errors if I use a virtual device. As soon as I try it in release mode on a physical device I get problems when it comes to the communication with the server
The only thing that I changed when using a physical device is the ip. I use 10.0.2.2 on the virtual device and my computers ip4 adress - that I get with ipconfig in windows 10 - on the physical device
Both devices are in the same network connected to the same router
Internet Permission is enabled in the AndroidManifest for all modes (Debug, Main, Profile)
I even disabled the firewall
The line that causes the issue is
await http.get(url).timeout(Duration(seconds: 15), onTimeout: () {
// Handle timeout
// This entire thing is in a try-catch block in an async function
});
In debug mode on the physical device when the HTTP get request is sent VSCode immediately says
Exception has occurred.
SocketException (SocketException: OS Error: Connection refused, errno = 111, address = 192.168.178.20, port = 43378)
First Question: Why Port 43378? Is that the port the HTTP request is sent to? Because when I run the flask app it says:
Running on http://127.0.0.1:5000/
Could that be the issue? I would have expected the exception to say the port is 5000 as declared in the URL. Or do I have to change something with how I set up the flask app? Currently it is the development server because I am still testing before I pay money and deploy
However I hope I didnt forget any important information. Any advice on what could be wrong or how to debug here is highly aprecciated
Pass an Uri object to http.get func. Uri classes let you specify the port as Documentation https://api.dart.dev/stable/2.12.0/dart-core/Uri-class.html
I'm having issues when trying to use bluetooth on my project. On previous version I used the HC-05 module for bluetooth and it gives me a simple serial connection right after any device connects. Now the project evolved and we opted on using SIM800H because it gives us GSM+Bluetooth.
When I connect any android device it gives me some profiles but never SPP. I can pair normally but when using any SPP server app (https://stackoverflow.com/a/4037619/2637661) I can never send or get data from my device. If I start the connection from the Android app, it says that it's connecting while the SIM800 gives me the URC and I respond:
+BTCONNECTING: "34:c7:31:aa:37:5b","SPP"
AT+BTACPT=1
OK
+BTCONNECT: 1,"Android",34:c7:31:aa:37:5b,"SPP"
But it stays on server mode and I can't use the commands AT+BTSPPSEND or AT+BTSPPGET, as the documentation says.
On the other hand, if I start the connection from my device just like the docs say:
AT+BTCONNECT=1,4 // Device is 1 and SPP profile is 4
OK
AT+BTSPPSEND
>I type anything here + ctrl+z
SEND FAIL
and get nothing on the Android side.
Plus in both cases the connection drops after something like 30s and I can't reestablish it unless I turn the SIM800H off and on again.
Got no success using the APP mode either (sending the string "SIMCOMSPPFORAPP" right after connection succeeds for transparent communication).
The SIM800H firmware version is
AT+CGMR
Revision:1309B07SIM800H32_BT
and I tried using the following apps
Bluetooth Terminal
Bluetooth spp pro
BlueSPP
The GSM side works flawlessly and I can send/receive TCP messages everytime I try.
Does anyone have any kind of experience using this module? Thanks for reading!
UPDATE:
I'm using a simple sketch in order to talk with the module's serial, don't know if it's relevant but here it goes.
#define SIM800_POWER 23
void setup() {
Serial.begin(9600);
Serial1.begin(19200);
Serial.print("Setting all up");
pinMode(SIM800_POWER, OUTPUT);
Serial.print(".");
delay(500);
digitalWrite(SIM800_POWER, HIGH);
Serial.print(".");
Serial.println("OK");
}
void loop() {
if(Serial1.available()){
Serial.write(Serial1.read());
}
if(Serial.available()){
Serial1.write(Serial.read());
}
}
And what I get after trying Andrii's answer:
Setting all up..OK
AT
OK
AT
OK
AT
OK
AT+BTPOWER=0
OK
AT+BTPOWER=1
OK
AT+BTCONNECT=1,4
OK
+BTCONNECT: 1,"Will",d4:87:d8:77:37:0b,"SPP"
AT+BTSTATUS?
+BTSTATUS: 5
P: 1,"Will",d4:87:d8:77:37:0b
C: 1,"Will",d4:87:d8:77:37:0b,"SPP"
OK
AT+BTSPPSEND
> SIMCOMSPPFORAPP
SEND FAIL
Seems AT+BTSPPSEND without any parameters is only for AT-command send from client (your SIM800H) to server (other SIM800, not your Android device unless your Android device implements AT-command support). For data sending you should use AT+BTSPPSEND and after receiving > symbol send SIMCOMSPPFORAPP keyword and then, after receiving SEND OK response send command AT+BTSPPSEND=<LENGTH_OF_YOUR_DATA> and then, after receiving > symbol, send your data until Ctrl+Z code e.g.:
AT+BTSPPSEND
> SIMCOMSPPFORAPP
SEND OK
AT+BTSPPSEND=5
> HELLO
SEND OK
^Z
where HELLO - is your data, and 5 in AT+BTSPPSEND=5 is length of HELLO string. Details in SIM800H_BT_Application_Note.
UPDATE
Selected by bold small, but important part of answer (thanks to hlovdal)
I am trying to start a server on Android using QTcpServer with Qt 5.3.1 but the server does not start and I get "Unsupported Socket Operation". It works fine on Windows.
Code below:
void StartListening()
{
QHostAddress hostAddress;
hostAddress.setAddress(QString("localhost"));
hostAddress.toIPv4Address();
quint16 portNumber = 9878;
server->setMaxPendingConnections(1);
server->setProxy(QNetworkProxy::NoProxy);
if (server->listen(hostAddress, portNumber))
{
// Ok
}
else
{
Debug("Server did not start. " + server->errorString());
}
}
server->errorString() returns "Unsupported Socket Operation when it runs on Android
Isn't this supported by Qt Android or am I doing something wrong?
Thx
OK! I worked it out.
The problem is with this line:
hostAddress.setAddress(QString("localhost"));
If I replace "localhost" with "127.0.0.1", the server starts fine but no one outside the "device the server is running on" can connect to it. This means, let's say your network is using 192.168.1.xx and your Android device has the following IP address: 192.168.1.2. If you start the server with "127.0.0.1" on your Android device which has an IP address: "192.168.1.2" and then using your PC with an IP address 192.168.1.3 you do telnet 192.168.1.2 9878 it will fail to connect!
So then I decided to start the server by specifying the IP address of the Android device: 192.168.1.2
hostAddress.setAddress(QString("192.168.1.2"));
Voila! That works too! The server starts and I can connect from outside the device! For example if I do telnet 192.168.1.2 9878 from my PC while the server is started on Android, it connects! So all I need to do now is replace the hard coded IP address with the actual IP address of the device! I think QNetworkInterface::allInterfaces() or something like that will give me the ability to get the default IP address.
So just use the actual IP address of the network card rather than localhost or 127.0.0.1 and all should be Ok. All working now.
I am willing to create a server and client program on my android mobile devices.
The devices communicate with each other on the same wifi network, therefore, some simple scanning mechanism must be implemented - The client phones search for a server phone through some kind of broadcast.
What I did:
My protocol - the client phone broadcasts a message port p on the wifi, the server listens on port p. when the server gets the broadcast message it sends a message back, therefore discovering itself to the client.
My code -
I have opened a broadcast socket on my app, it sends a broadcast message.
Meanwhile there is a python script on my PC that listens and replies - I use python so that my testing will be easier - Wireshark on the PC and I can see everything.
What happens:
When I use one of my Galaxy S phones - it works and I get a response.
When I use the other Galaxy S phone - it doesn't work.
Now this is what I know:
The phone that works actually has Nexus ROM on it Ver. 4.1.1
The phone that doesn't work has 2.3.3 regular galaxy ROM
The python code says it receives both of the broadcasts sent from both phones, and replies to both of them without raising any exception.
So far I was thought the problem may be
1. the older version'd phone.
2. the windows firewall
3. the router firewall
So I have opened Wireshark, and Indeed I saw that both phones are sending their broadcasts - it was logged on Wireshark.
But the python script only responded to the first one.
So this is why 1 & 3 are irrelevant - if the router firewall was blocking my UDP I would have still seen the python server response, same with the older versioned phone.
To get rid of 2 i just disabled the windows firewall - still same problem.
Does anyone has a clue to why this effect might happen?
Thanks!
Edit
My python code:
def scan(data, addr, sock):
print "received scan message:", data, addr
name = u"name".encode("utf-16-le")
data = "DISC" + short2bytes(len(name)) + name
print "sending back %s to %s" % (data, addr)
sock.sendto(data, addr)
if __name__ == "__main__":
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(('', UDP_PORT))
while 1:
data, addr = sock.recvfrom(1500)
print "received packet " + data
if data.startswith("SCAN"):
scan(data, addr, sock)
edit 2:
Okay! Seems like my code and protocol DID work.
As it turns out the 2.3.3 phone had some severe ARP problems.
After some resets it works flawlessly!
I am trying to make a way to telnet to an unrooted Droid. I have the INTERNET permission active, I have my device connected on the same network as my Mac OS X box via WiFi, and I am able to ping the port I opened.
In initial experiments, I got it to work on a rooted test device, but I had the socket handlers run on the UI Thread rather than a separate thread. Now that I have the network modules on a separate thread, I can't get ServerSocket.accept () to return. It works on Google's version of android (vanilla), but not on Samsung's or Sony-Ericsson's.
When I telnet to it, my attempt would time out, and logcat wouldn't print out any exceptions or errors.
Here is a link to a google-code repo of my code: Google-code Repository
I am running ServerScoket.accept () on a separate thread, and run the stream processors on another thread as well. Comments on my design (i.e. I should use Handlers or AsyncTasks) are extremely welcome. Right now, in order to Toast the messages received via telnet, I use a Handler with the looper being acquired via a Context.
The following is what I get when I run netstat -n on the adb shell on the non-working devices:
~$ adb shell netstat -n
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 127.0.0.1:7777 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:7203 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:47609 127.0.0.1:7777 ESTABLISHED
tcp 0 0 127.0.0.1:7777 127.0.0.1:47609 ESTABLISHED
tcp 0 0 127.0.0.1:47610 127.0.0.1:7777 ESTABLISHED
tcp 0 0 127.0.0.1:7777 127.0.0.1:47610 ESTABLISHED
The difference is that in the working devices, they list an IP with my port open in the state, LISTEN.
UPDATE: Having the <uses-permission android:name="INTERNET"/> set in my android_manifest, I tried changing the port number to 689. It didn't work; I got a BindException, saying that I may be lacking the INTERNET permission. So, I changed it to 1989, and I went back to everything working until accept (). I assume this is because I ran it on a non-root phone, and I don't have access to ports 1024 and below.
UPDATE: I ran a really similar program on my Mac, and it worked fine when I tried telnetting to my Mac using the IP address assigned to me. It didn't work when I tried telnetting from another Mac but it didn't seem to connect; the connection would timeout. It did work over an ad-hoc network, though. I still have yet to try it using the droid, but I will update this asap.
UPDATE: I managed to get the app working on 3 separate Droids running Vanilla (Android released by google). It worked on a Nexus, an Apanda A60 (my first device; adb has ceased to detect it for some reason.), and a custom-made, unbranded tablet. Still, because I already offered a pretty big bounty, I plan on seeing this through to the end.
As stated earlier, my app works with Vanilla versions of android, but not with modified versions. The three phones that failed to run it were all mid-range models; 2 Samsung GT-i5503s, and a Sony-Ericcson E16i.
It seems like you have a networking issue, rather than a code issue. I used your latest project and it is listening on the port, as expected.
I added this to TelnetServer.setupServerSocket() to confirm some information:
Log.i("TelnetServer", "ServerSocket Address: " + this.server.getLocalSocketAddress());
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
Log.i("TelnetServer", "Listen On: " + inetAddress.getHostAddress());
}
}
} catch (SocketException ex) {
Log.e("TelnetServer", ex.toString(), ex);
}
This will print all of the addresses your service is listening on (if it is listening on 0.0.0.0/0.0.0.0:xxx (printed after ServerSocket Address:)).
You should run emulator with the -tcpdump <file> option and also provide this. It will confirm any connection is being attempted. My hunch is that your client is not able to access the server, which is why the server is not receiving the connection - rather than an issue with the code.
Please provide the tcpdump file, your IP Address (of the client) and the logcat output (including the ServerSocket Address and Listen On statements) for further analysis.
See if netstat -n from the adb shell shows anything actually listening on the port you chose at the time when accept() is not returning.
Also realize that when not running as root, you can only bind unprivileged ports, of which the default telnet port is not an example. Does your code check that bind() was successful?
UPDATE:
Since the code works on a number of devices (where netstat -n would presumably list the socket) the failure to list it on the subject device should probably remain a focus. The Java ServerSocket methods depend on a socket factory which can be over-ridden to let you do distinct calls to socket(), bind(), and listen() specifying fuller details, so it may make sense to try your code that way. There's another case floating around where a device's attempt to support ipv6 seems to be causing someone similar problems, and at least on other java platforms creating the socket at a lower level to specify ipv4 seems like a promising answer.
I understand you have tried most of the things are you are just few steps from getting it right on two particular devices.
Just a thought, If not point to point, why not Use Muti-casting for service registration and discovery in local area networks.
This is the java implementation JmDNS
and this is its Android demo
EDIT : Rather I should say to check connectivity with that two devices.