sl4a, problems with reading (bluetooth) - android

I am trying to write a script, which will connect a device (radiomodem), that have a bluetooth with my Nexus 7 (Android 4.4)
The task is to send a command via bluetooth, and then get an answer from radiomodem.
After sending a command I don't get an answer from device (or I get it, but cannot read bluetooth buffer), and my script stops while reading. It doesn't send me any mistakes, just stops.
I've tried to send commands from Nexus to PC, and I've seen them in virtual COM on PC.
I've tried to send from PC to Nexus, and from radiomodem to Nexus long lines and read them. it was fine, too.
But writing-reading doesn't work. What I'm doing wrong?
Here is my code:
import sl4a
import time
droid = sl4a.Android()
uuid = '00001101-0000-1000-8000-00805F9B34FB'
adr = '6B:E2:00:DA:18:01'
droid.toggleBluetoothState(True) # connection is always successful
droid.bluetoothConnect(uuid,adr)
time.sleep(2)
i = 0
while i < 3:
res = droid.dialogGetInput().result
res = res + '\r'
droid.bluetoothWrite(res)
time.sleep(0.6) # here I've tried different timeouts
ans = droid.bluetoothRead(4096).result
if ans is None:
print('no answer')
else:
w = str(ans)
droid.dialogCreateAlert("+", w)
droid.dialogSetPositiveButtonText('OK')
i += 1

Half a year ago I did a small app with PY4A and I had trouble with connecting to my Bluetooth heart rate monitor from a galaxy S2. To solve the connection issue's I switched to pybluez. Using the Bluetooth device worked from there. See the working example that helped me here.
http://cuu508.wordpress.com/2011/02/21/hxm-t-display-heart-rate-from-zephyrs-hxm/
I hope this helps.
Regards.

Related

Python Bluetooth: Can't get android to print connected device name

I'm fairly new to python SL4A and I could not find a question that helped me, so bear with me.
Here is what I'm working with so far:
import sl4a
UUID = ''
droid = sl4a.Android()
droid.toggleBluetoothState(True, False)
droid.bluetoothConnect(UUID)
print(droid.bluetoothGetConnectedDeviceName())
Here is the error that I get when I run the above code:
"java.io.IOException: Bluetooth not ready for this connID."
If I run the above code without the last line, I can see on my laptop that it's connected, but I want to see from the android's side that I can return the device name (for shits n' gigs).
What am I doing incorrectly so that I can get the android to return the device's name?
Edit: Please let me know if I should ask in a different manner; this is my first post, but I regularly troll this website for answers when I come to a roadblock.

Python Bluetooth how to send a file to a phone

in my current project it is a requirement to send a file from a windows computer to an android device over bluetooth without anything on the phone other than it's standard state and of course a paired bluetooth connection. i've looked over pybluez and it seemed simple enough to send files between a client and server architecture (and in fact got it sending between my laptop and desktop rather quickly) but I cannot for the life of me find any way to get python to send a file from the computer to android once the connection is established; my attempts have been grabbing the bluetooth mac address like thing from the device like so
nearby_devices = bluetooth.discover_devices(
duration=8, lookup_names=True, flush_cache=True, lookup_class=False)
and then later trying to send the files like so
port = 1
for addr, name in nearby_devices:
bd_addr = addr
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
sock.send("download-app")
sock.close()
Of course with the example script given by the pybluez documentation I can seamlessly send files between a client and a server but I am still stuck without a way to send a file to the selected android device (even if I specify it's address and know it's within range)
You're most of the way there...
As you know, you need something to talk to at the other end of your Bluetooth connection. You just need to replace your custom server with a well-known service (generally one of these options).
In my case, my phone supports the "OBEX Object Push" service, so I just need to connect to that and use a suitable client to talk the right protocol. Fortunately, the combination of PyOBEX and PyBluez does the trick here!
The following code (quickly patched together from PyOBEX and PyBluez samples) runs on my Windows 10, Python 2.7 installation and creates a simple text file on the phone.
from bluetooth import *
from PyOBEX.client import Client
import sys
addr = sys.argv[1]
print("Searching for OBEX service on %s" % addr)
service_matches = find_service(name=b'OBEX Object Push\x00', address = addr )
if len(service_matches) == 0:
print("Couldn't find the service.")
sys.exit(0)
first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]
print("Connecting to \"%s\" on %s" % (name, host))
client = Client(host, port)
client.connect()
client.put("test.txt", "Hello world\n")
client.disconnect()
Looks like PyOBEX is a pretty minimal package, though, and isn't Python 3 compatible, so you may have a little porting to do if that's a requirement.
I haven't personally explored it but check out this blog -
http://recolog.blogspot.com/2013/07/transferring-files-via-bluetooth-using.html
The author uses the lightblue package as an API for the Obex protocol and send files over the connection. Now the lightblue package appears to be unmaintained. There are other packages like PyObex (which I could not import for whatever reason) which you could also explore as alternatives but lightblue seems to be the way to go.
I have made a Python 3 port of PyOBEX based on the PyOBEX code on bitbucket. I've tested so far only the client functionalities, but I expect the server to be working fine as well, since most of the compatibility issues with Python 3 were due to struct.pack/struct.unpack binary blobs appended to strings that should have all been tackled.

Strophe.js does not connect to openfire

I set up an openfire server on a server within our network and gave it a domain name. I want to connect to it via my phone in a phonegap app and therefore implemented a strophe.js client within my app.
It works fine on my Nexus 5 (Android 4.4.3), but as soon as I want to run it on my Samsung Galaxy S2 (Android 4.1.2) or the Samsung Galaxy Tab (GT-P7501 - Android 4.0.4) I don't get any response from the server. Here is the code snippet of my connect:
var BOSH_SERVICE = 'http://SERVERNAME:7070/http-bind/';
var connection = null;
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE);
connection.rawOutput = log;
connection.rawInput = log;
connection.connect('id#servername/resource', 'test', onConnect);
});
function log(msg) {
console.log(msg);
}
function rawInput(data) {
log('RECV: ' + data);
}
function rawOutput(data) {
log('SENT: ' + data);
}
the console log will be:
SENT: <body rid='367573377' xmlns='http://jabber.org/protocol/httpbind' to='servername' xml:lang='en' wait='60' hold='1' content='text/xml; charset=utf-8' ver='1.6' xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'/>
This will be repeated a few times but I don't get any incoming messages. The servers version number is openfire 3.9.3. As all this code works on my nexus 5 I assume that the code is correct. I Also doubt that my server is configured wrong, nevertheless I included a screenshot of the config settings of the openfire server in the end.
The openfire xmpp server is running on a windows server and I access it via wifi/dyndns.
Do you have any ideas why this does not work on the samsung galaxy? Every help will be appreciated. Thanks in advance !
I could "solve" this by myself. It is really not a big deal, but it took me a really long time (3 days) to realize this, so in case anyone will ever come accross the same phenomena this info might help:
In my case all the configurations of the server and the strophe client above are correct. Indeed the only reason the connect did not work properly on all devices seemed to be that these devices could not even ping the server, even though they are in the same network. In my case I gave the server a static domain name, which was the key issue. Somehow the Google Nexus 5 is able to resolve this name to an ip adress via the dns-server, but both the elder samsung galaxy s2 and the samsung galaxy tab aren't.
Solution: I replaced the static domain name with the corresponding ip-adress in my strophe.js connection.

Receiving UDP on different Android phones gives different results

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!

multicastlock not working on Android 2.2 phone

I need to be able to receive broadcasts on the Wifi of this phone. It's an HTC Desire, about 2 years old, running Android 2.2.
I've followed the docs and some example code I found, and ended up with this code to enable the multicast:
mWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock multicastLock = mWifiManager.createMulticastLock("net.inside.broadcast");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
Log.i("BCXXX", "multicastLock.isHeld() = " + multicastLock.isHeld());
Log.i("BCXXX", "multicastLock.toString() = " + multicastLock.toString());
The log output follows here:
I/BCXXX ( 3302): multicastLock.isHeld() = true
I/BCXXX ( 3302): multicastLock.toString() = MulticastLock{ 45fa2b88; held; refcounted: refcount = 1 }
This seems to confirm that the multicastLock should be held, meaning multicast should work. However, it doesn't. The Android app simply does not receive any broadcast packets except for its own, i.e. the one it sends out to the others. The other machines I should mention can see the Android phone just fine and receive its broadcast messages. I've tried addressing the packets to 255.255.255.255 as well as 192.168.0.255 (with 192.168.0. obviously being the net everyone is connected to in the LAN).
This is a project built with Unity 3.5 and both the Windows and OS X builds work as expected. The Android plugin does get called (as is evident from the log entries).
Any ideas anyone?

Categories

Resources