Hello,
Here's a piece of code (messy) where I'm using non-blocking BT sockets. Seems to work fine. I've PyS60 1.3.1.
Code:
import socket
import thread
import e32
import appuifw
import pyS60uiutil
def service_discovery():
try:
addr, serv = socket.bt_discover()
if addr == None or serv == None:
appuifw.note(u'BlueTooth Discovery Error', 'error')
return None
print 'got address...'
choises = serv.keys()
choises.sort()
lst = []
for x in choises:
lst.append(unicode(str(x)+u' #'+str(serv[x])))
choice = appuifw.popup_menu(lst)
if choice == None: return None
print 'Selected service: ' + str(addr) + ' ' + \
str(serv[choises[choice]])
except socket.error, detail:
err_msg = u'BlueTooth socket error: ' + unicode(detail)
appuifw.note(err_msg, 'error')
return None
return (addr, serv[choises[choice]])
def create_connection(address):
appuifw.note(u'Creating connection', 'info')
sock=socket.socket(socket.AF_BT,socket.SOCK_STREAM)
try:
sock.connect(address)
except socket.error, err:
if err[0]==54: # "connection refused"
appuifw.note(u'Connection refused.','error')
return None
raise
appuifw.note(u'Cool, you are connected!', 'info')
return sock
class main:
def __init__(self, sock):
self.timer = e32.Ao_timer()
self.lock = e32.Ao_lock()
self.sock = sock
self.do_exit = False
appuifw.app.exit_key_handler = self.myexit
self.sock.setblocking(False)
def myexit(self):
self.do_exit = True
self.timer.cancel()
self.lock.signal()
appuifw.app.exit_key_handler = None
def timeout_h(self):
rxmsg = self.sock.recv(1024)
if rxmsg == None or rxmsg == '':
print 'no msg'
#pass
else:
appuifw.note(unicode(rxmsg), 'info')
self.lock.signal()
def run(self):
while 1:
self.timer.after(0.5, self.timeout_h)
self.lock.wait()
if self.do_exit: break
if __name__ == '__main__':
ai = pyS60uiutil.save_current_app_info()
addr = service_discovery()
if not addr == None:
sock = create_connection(addr)
if not sock == None:
m = main(sock)
m.run()
sock.close()
pyS60uiutil.restore_app_info(ai)