Unstable behaviour of Pybluez on different devices - Python - python

I have 3 devices -> 2*PC and 1 Raspberry Pi. 2 PCs are only for the sake of testing. 2PC = 2 Laptops with Windows 10.
On raspberry pi I have Bluetooth service(Py 2.7 but 3.5 should also work if print()):
import bluetooth
try:
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
server_sock.bind(("",0))
server_sock.listen(100)
bluetooth.advertise_service( server_sock, "MyService",
service_classes = [ bluetooth.SERIAL_PORT_CLASS ],
profiles = [ bluetooth.SERIAL_PORT_PROFILE ] )
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
client_sock.send('Hello')
data = client_sock.recv(1024)
print("received [%s]" % data)
client_sock.close()
server_sock.close()
except:
client_sock.close()
server_sock.close()
On Laptops I have client
import sys
from bluetooth import *
try:
service_matches = find_service(name="MyService",
uuid = SERIAL_PORT_CLASS )
print(service_matches)
if len(service_matches) == 0:
print('Found nothing')
sys.exit(0)
for i in service_matches:
print(i)
first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]
print "connecting to ", host
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))
data = sock.recv(1024)
sock.send("hello!!")
print(data)
sock.close()
except Exception as e:
print(e)
sock.close()
Everything works just fine, however, with one laptop I can repeat the proces between listening and connecting forever. With other Laptot I am able to connect 2-3 times and then I am receiving this error:
in <module>
uuid = SERIAL_PORT_CLASS )
File "C:\Python27\lib\site-packages\bluetooth\msbt.py", line 204, in find_service
addresses = discover_devices (lookup_names = False)
File "C:\Python27\lib\site-packages\bluetooth\msbt.py", line 15, in discover_devices
devices = bt.discover_devices(duration=duration, flush_cache=flush_cache)
IOError: No more data is available.
That means the error happened inside the pybluez function find_service. Interesting is that this happens when it cannot find a device. On the other laptop where this error is never triggered(always connects) but there are no devices ends up always with:
print('Found nothing')
When the error starts to happen after 2-3 succesful connections, I need to restart Raspberry pi to be able to connect again.
Thanks for any help

Related

Python socket issue when connecting to raspberry pi

I am trying to do wireless communications between a PC (windows) and a Raspberry Pi 3 using python's socket module. The server is the PC and the client is the Pi. When I run the code (server first then client) both scripts get stuck after "hey, checking TCP socket".
When I do the reverse (Pi being the server and PC being the client) the code works fine, with data been sent correctly.
Both the PC and Pi are connected to the same network. The IP address of PC is 10.0.0.198 and the Pi is 10.0.0.63.
I think the problem is that the port is not open when I use my PC as a server. How to resolve this?
My client script:
import socket
import sys
def read(port):
s = socket.socket()
host = '10.0.0.198' #(IP address of PC (server))
s.connect((host,port))
try:
msg = s.recv(1024)
s.close()
except socket.error, msg:
sys.stderr.write('error %s'%msg[1])
s.close()
print 'close'
sys.exit(2)
return msg
if __name__ == '__main__':
port = 1025
while True:
print 'hey, checking TCP socket'
data = read(port)
print 'i just read %s' % data
print 'port num is: %d' % port
port = port + 1
My server script:
import socket
import time
def send(data, port):
s = socket.socket()
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print 'Got connection from',addr
c.send(data)
c.close()
if __name__ == '__main__':
port = 1025
num = 1
while True:
print 'hey, sending data'
words = 'helloWorld'
data = words + str(num)
print 'send data: %s' % data
send(data,port)
port = port + 1
num = num + 1

OSError with Pybluez librairy

I would like to make a bluetooth communication between a laptop with a bluetooth dongle and windows 7, and my raspberry pi 3.
I found on internet some tutorials which use the Pybluez librairy but this doesn't work for me.
Find below the code for the server part :
import bluetooth
Host = ""
port = 12
HostAddr = (Host, port)
def setupServer():
server_socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
print("Socket Created.")
server_socket.bind(HostAddr)
server_socket.listen(1)
print("Socket bind complete")
client_sock, client_info = server_socket.accept()
print("Accepted connection from " , client_info)
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print("received [%s]" %data)
except IOError:
pass
print("Disconnected")
client_sock.close()
server_socket.close()
print("all done")
setupServer()
This is the output :
Socket Created.
Traceback (most recent call last):
File "path_to_file\Server.py", line 33, in <module>
setupServer()
File "path_to_file\Server.py", line 12, in setupServer
server_socket.bind(HostAddr)
File "C:\Python34\lib\site-packages\bluetooth\msbt.py", line 60, in bind
bt.bind (self._sockfd, addr, port)
OSError
Do you have an idea why i had this error ?

python Bluetooth error - No module named _bluetooth

I am trying an example code in python which works as a bluetooth server. This code gives following error..
Traceback (most recent call last):
File "/var/lib/cloud9/examples/Sa/rfcomm-server_py", line 7, in
from bluetooth import *
File "/var/lib/cloud9/examples/Sa/bluetooth/init.py", line 43, in
from .bluez import *
File "/var/lib/cloud9/examples/Sa/bluetooth/bluez.py", line 6, in
import _bluetooth as _bt
ImportError: No module named _bluetooth
I am using beaglebone green wireless board in cloud9 IDE
# file: rfcomm-server.py
# auth: Albert Huang <albert#csail.mit.edu>
# desc: simple demonstration of a server application that uses RFCOMM sockets
# $Id: rfcomm-server.py 518 2007-08-10 07:20:07Z albert $
from bluetooth import *
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
advertise_service( server_sock, "SampleServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
# protocols = [ OBEX_UUID ]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print("received [%s]" % data)
except IOError:
pass
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
I didn't turn on the bluetooth on Beaglebone green wireless board, but after running the following command, the code above worked perfectly:
$ bb-wl18xx-bluetooth

Connection refused when trying to connect to bluetooth server

I am trying to build a simple Bluetooth client / server where my Raspberry Pi is the server and my laptop the client.
This is the server code (running on my Raspberry Pi):
#!/usr/bin/python
# -*- coding: utf-8
import wifi, bluetooth
uuid="1e0ca4ea-299d-4335-93eb-27fcfe7fa848"
print "Setting up Bluetooth socket"
try:
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.bind(("", 0))
sock.listen(1)
except IOError as e:
print str(e)
print "Registering service"
try:
bluetooth.advertise_service(sock, "MyService", uuid)
while True:
print "Waiting for connection..."
client_sock,address = sock.accept()
print "Accepted connection from {0}".format(address)
data = client_sock.recv(1024)
print "Received data: {0}".format(data)
print "Closing client socket."
client_sock.close()
except IOError as e:
print str(e)
This seems to work, the script runs and blocks with Waiting for connection....
Then, my client code:
#!/usr/bin/python
# -*- coding: utf-8
import bluetooth, time
mac = "00:15:83:E5:E2:46"
uuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848"
service = []
retry = 1
while len(service) == 0:
print "Looking for service on {0}, try {1}".format(mac, retry)
service = bluetooth.find_service(address=mac, uuid=uuid)
retry = retry + 1
time.sleep(1)
if len(service) == 1:
service = service[0]
print "Service found. Name={0}".format(service["name"])
print "Connecting to service."
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
try:
sock.connect((mac, service["port"]))
print "Connected to service on {0} on port {1}".format(mac, service["port"])
except bluetooth.btcommon.BluetoothError as e:
print "Connection failed: {0}".format(e)
elif len(service) == 0:
print "No service found on mac {0}.".format(mac)
else:
print "{0} services found for mac/uuid, ignored.".format(len(service))
Also works, up until I try to connect() to the Raspberry Pi. I get the following error:
Connecting to service.
Connection failed: (111, 'Connection refused')
I tried connecting the laptop to the Raspberry Pi (it finds it and says it is "Connected") and searching for more info online, but wasn't able to find anything.
This error occures when u want to connect to not listening port.
U are listening on port "0" .....
Change it to for example 9999 and then client has to connect to that port on the server adress

RFCOMM without pairing using PyBluez on Debian?

I am trying to create an RFCOMM server process with Python that can be used without the need for pairing. Initially, I grabbed the two example scripts from the PyBluez documentation:
Server:
# file: rfcomm-server.py
# auth: Albert Huang <albert#csail.mit.edu>
# desc: simple demonstration of a server application that uses RFCOMM sockets
#
# $Id: rfcomm-server.py 518 2007-08-10 07:20:07Z albert $
from bluetooth import *
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
advertise_service( server_sock, "SampleServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
# protocols = [ OBEX_UUID ]
)
print "Waiting for connection on RFCOMM channel %d" % port
client_sock, client_info = server_sock.accept()
print "Accepted connection from ", client_info
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print "received [%s]" % data
except IOError:
pass
print "disconnected"
client_sock.close()
server_sock.close()
print "all done"
Client:
# file: rfcomm-client.py
# auth: Albert Huang <albert#csail.mit.edu>
# desc: simple demonstration of a client application that uses RFCOMM sockets
# intended for use with rfcomm-server
#
# $Id: rfcomm-client.py 424 2006-08-24 03:35:54Z albert $
from bluetooth import *
import sys
addr = None
if len(sys.argv) < 2:
print "no device specified. Searching all nearby bluetooth devices for"
print "the SampleServer service"
else:
addr = sys.argv[1]
print "Searching for SampleServer on %s" % addr
# search for the SampleServer service
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
service_matches = find_service( uuid = uuid, address = addr )
if len(service_matches) == 0:
print "couldn't find the SampleServer 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)
# Create the client socket
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))
print "connected. type stuff"
while True:
data = raw_input()
if len(data) == 0: break
sock.send(data)
sock.close()
When I ran the server script on Windows everything worked just how I had hoped - no pairing was necessary. At this stage everything was looking very promising.
However, I need the server process to run under Debian Squeeze. When I test on Debian the client connection is refused. In the syslog there are messages from bluetoothd for a failed link key request and PIN request.
Version information:
PyBluez 0.18
Python 2.6
Bluez 4.66
Bluetooth v2.0 hardware on both ends of the connection
This discussion seems to suggest that if I can adjust the security level on the server socket then pairing will be disabled and everything will just work as expected. It is not apparent to me how to do this with PyBluez though, or even if it is possible.
I have experimented with calls to setsockopt() using various BT_SECURITY* constants, as well as grabbing the last PyBluez and calling setl2capsecurity() but have not been able to make any progress.
Is this going to be achievable with PyBluez?
This turned out to be a problem with the Debian Squeeze bluez default configuration.
If anyone else hits this problem, disable the pnat plugin by editing /etc/bluetooth/main.conf:
DisablePlugins = pnat
Then restart bluetoothd.
$ sudo invoke-rc.d bluetooth restart
No changes were required to the PyBluez code.

Categories

Resources