×

Discussion Board

Results 1 to 14 of 14
  1. #1
    Regular Contributor
    Join Date
    Mar 2008
    Posts
    151

    Bluetooth comms - make event driven

    This basic code accepts commands from my PC sent over BT. At the moment it just loops and loops waiting from strings to come through.

    How do I get it to fire a function whenever a bluetooth string is received, so it can sit idle until something is received?

    Thanks.

    Code:
    import socket
    
    PCadd=('00:15:83:b7:08:57', 2)
    
    sock=socket.socket(socket.AF_BT, socket.SOCK_STREAM)
    target=(PCadd)
    sock.connect(target)
    
    print 'Connected to ' + str(PCadd)
    
    while 1:
    	data = sock.recv(1024);
    	if not data: break
    	print data
    sock.close()

  2. #2
    Regular Contributor
    Join Date
    Nov 2007
    Posts
    147

    Re: Bluetooth comms - make event driven

    I was just looking at something similar. In theory it should work by using the following:
    1. Threading
    2. Callback function

    Here is a sample that works on a pc:

    Code:
    import time
    from threading import Thread
    
    class Test(Thread):
        def __init__(self):
            self.callback = None
            self.id = 0
            Thread.__init__(self)
    
        def run(self):
            start = time.time()
            dif = time.time()-start
            i1 = time.time()
            while dif < 20:
                dif = time.time()-start
    
                i2 = time.time()
                if (i2-i1 > 1):
                    i1 = time.time()
                    #print i1
                    self.callback("This is an event from thread: %s" % self.id)
    
    
    def event_fired(*args):
        print args[0]
    
    if __name__ == '__main__':
        start = time.time()
        t1 = Test()
        t1.id=1
        t1.callback = event_fired
    
        t2 = Test()
        t2.id=2
        t2.callback = event_fired
    
        t3 = Test()
        t3.id=3
        t3.callback = event_fired
    
    
        print "started"
        t1.start()
        t2.start()
        t3.start()
    
        t1.join()
        t2.join()
        t3.join()
    
        print "end"

  3. #3
    Regular Contributor
    Join Date
    Mar 2008
    Posts
    151

    Re: Bluetooth comms - make event driven

    Sorry....I don't really get it! I don't know anything about threads etc on Python, or in any language for that matter. If anyone can explain I'd be grateful. I've read about a .listen function, but it's not documented in the 1.4.2 library reference.

  4. #4
    Regular Contributor
    Join Date
    Nov 2007
    Posts
    147

    Re: Bluetooth comms - make event driven


  5. #5
    Registered User
    Join Date
    Jan 2007
    Location
    Spain
    Posts
    21

    Re: Bluetooth comms - make event driven

    Hello

    Have you checked "select" módule?

    This code must work for reading ip sockets but
    i don't now about BT sockets.


    Code:
    import socket
    import select
    
    PCadd=('00:15:83:b7:08:57', 2)
    
    sock=socket.socket(socket.AF_BT, socket.SOCK_STREAM)
    target=(PCadd)
    sock.connect(target)
    
    print 'Connected to ' + str(PCadd)
    
    timeout = 5 # 5 seconds
    while 1:
            l = select.select([sock],[],[],timeout)
            if not l: continue
    	data = sock.recv(1024);
    	if not data: break
    	print data
    sock.close()

  6. #6
    Registered User
    Join Date
    May 2008
    Posts
    15

    Thumbs down Re: Bluetooth comms - make event driven

    Hi everyone,

    Ive been playing with thread somehow to retrieve the bluetooth messages in an asynchronous way. Well after blocking the nokia n95 few times and even had to take the battery out, I would like some tips if anyone knows anything more about threads.

    So Ive been playing with the code given here

    Here is my code:
    Code:
    #single line comment
    """multiline comment"""
    
    #Api importations
    import sys
    sys.path.append('e:\\python\\lib')
    import e32 
    import socket
    import appuifw
    from appuifw import *
    import threading
    
    class MyThread ( threading.Thread ):
    
    	def run ( self ):
    		global sock
    		print 'Entered in thread'
    		try:
    			sock.send("Hello World")
    			print 'no error while sending'
    		except:
    			print 'error while sending'
    		print 'Leaved the thread'
    		
    def quit():
    	global sock
    	try:
    		sock.close()
    		appuifw.note(u"Socket aus.","info")
    		app_lock.signal()
    	except NameError:
    		appuifw.note(u"Socket war nicht an.","info")
    		app_lock.signal()
    
    def connect():
    	global sock
    	sock=socket.socket(socket.AF_BT, socket.SOCK_STREAM)
    	sock.connect(('00:0e:9b:d9:5d:a2',1))	
    
    def launchThread():
    	MyThread().start()
    
    
    #Code implementation
    menu=appuifw.app.menu=[	(u"Quit",quit),
    						(u"Connect",connect),
    						(u"Start Thread",launchThread)]
    
    print 'Connection starting...'
    connect() #connect to the computer id hyperterminal
    print 'Wait to be connected...'
    e32.ao_sleep(5) #wait to be sure to be connected
    print 'Starting thread...'
    app_lock=e32.Ao_lock()
    appuifw.app.exit_key_handler=quit
    MyThread().start()
    app_lock.wait()
    #end of the program
    Basically everything goes well till Entered Thread, and then nothing happens, the Python Console freeze and I have to wait till the Python Console crashes, and basically just closes. No error message, nothing since it bugged. Could anyone help me on that, Im sure the problem comes from send(), because whatever I put in this thread it is working, but as soon as i put the send() method then, doesnt work anymore...

    Cheers,

    fran

  7. #7
    Regular Contributor
    Join Date
    Dec 2007
    Location
    India
    Posts
    133

    Re: Bluetooth comms - make event driven

    Quote Originally Posted by jtullis View Post
    This basic code accepts commands from my PC sent over BT. At the moment it just loops and loops waiting from strings to come through.

    How do I get it to fire a function whenever a bluetooth string is received, so it can sit idle until something is received?

    Thanks.

    Code:
    import socket
    
    PCadd=('00:15:83:b7:08:57', 2)
    
    sock=socket.socket(socket.AF_BT, socket.SOCK_STREAM)
    target=(PCadd)
    sock.connect(target)
    
    print 'Connected to ' + str(PCadd)
    
    while 1:
    	data = sock.recv(1024);
    	if not data: break
    	print data
    sock.close()
    Have you tried the any of the debugging techniques to find out due to which error the python shell is crashing?

    You could use the exception harness method to do it, or any of the method from this article
    Kandyfloss

    V 7.0642.0
    18-10-06
    RH-51
    Nokia 7610

  8. #8
    Regular Contributor
    Join Date
    Mar 2008
    Posts
    151

    Re: Bluetooth comms - make event driven

    I wonder if
    Code:
    sock.send("Hello World")
    needs a 'u' before the string?

    Code:
    sock.send(u"Hello World")

  9. #9
    Registered User
    Join Date
    May 2008
    Posts
    15

    Unhappy Re: Bluetooth comms - make event driven

    So I tried the different debugging techniques, but the problem is that not any exception are thrown out, so impossible to catch them.

    Here is my code...
    Code:
    try:
        # Actual program is here.
    	#Code implementation
    	menu=appuifw.app.menu=[	(u"Quit",quit),
    							(u"Connect",connect),
    							(u"Start Thread",launchThread)]
    	# Set up the server:
    	server = socket.socket ( socket.AF_BT, socket.SOCK_STREAM )
    	adress='00:0e:9b:d9:5d:a2'
    	app_lock=e32.Ao_lock()
    	appuifw.app.exit_key_handler=quit
    	print 'Connection starting...'
    	server.connect((adress,1))
    	#time=server.gettimeout()
    	#print 'Time out', time
    	print 'Wait to be connected...'
    	e32.ao_sleep(5) #wait to be sure to be connected
    	print 'Connected...'
    	ClientThread ( server, adress ).start()
    	print 'wait before going to wait!'
    	e32.ao_sleep(10)
    	print 'wait now hoping thread launched'
    	app_lock.wait()
    	#End of program
    	1 / 0
    except:
    	import sys
    	import traceback
    	import e32
    	import appuifw
    	appuifw.app.screen="normal"               # Restore screen to normal size.
    	appuifw.app.focus=None                    # Disable focus callback.
    	body=appuifw.Text()
    	appuifw.app.body=body                     # Create and use a text control.
    	applock=e32.Ao_lock()
    	def quit():applock.signal()
    	appuifw.app.exit_key_handler=quit         # Override softkey handler.
    	appuifw.app.menu=[(u"Exit", quit)]        # Override application menu.
    	body.set(unicode("\n".join(traceback.format_exception(*sys.exc_info()))))
    	applock.wait()                            # Wait for exit key to be pressed.
    	appuifw.app.set_exit()
    As u can see, i tried to put some temporisation to be sure everything is started, but anyway after seeing on the console the message: Received connection blabla, then everything freezes, i can barely go back to the menu of the nokia n95, and anyway python shell doesnt work any more, and still no error message?!

    Anyone idea?

    cheers,
    fran

  10. #10
    Registered User
    Join Date
    May 2008
    Posts
    12

    Re: Bluetooth comms - make event driven

    I had seen somewhere a procedure that allowed to make a text file which would work as the error log?
    Where could I find it?

    Thanks

  11. #11
    Nokia Developer Moderator
    Join Date
    May 2007
    Location
    21.46 N 72.11 E
    Posts
    3,800

    Re: Bluetooth comms - make event driven

    Quote Originally Posted by reallife47 View Post
    I had seen somewhere a procedure that allowed to make a text file which would work as the error log?
    Where could I find it?

    Thanks
    You could use the below code for that,

    Code:
    def main():
        try:
            Your main code goes here.
        except:
            import sys
            import traceback
            import appuifw
            cla, exc, trbk = sys.exc_info()
            excName = cla.__name__
            try:
                excArgs = exc.__dict__["args"]
            except KeyError:
                excArgs = "<no args>"
            excTb = traceback.format_tb(trbk, 5)
            errorString = repr(excName) + '-' + repr(excArgs) + '-' + repr(excTb) + '\n'
            print errorString
            appuifw.note(u'Application errors, see log file for more information', "error")
            file = open(u'C:\\Log.txt','a')
            file.write(errorString)
            file.close()
            raise
     
    if __name__ == "__main__":
        main()
    Errors would be recorded to C:\\Log.txt

    Best Regards,
    Croozeus
    Pankaj Nathani
    www.croozeus.com

  12. #12
    Super Contributor
    Join Date
    Mar 2003
    Location
    Espoo, Finland
    Posts
    976

    Re: Bluetooth comms - make event driven

    Quote Originally Posted by reallife47 View Post
    I had seen somewhere a procedure that allowed to make a text file which would work as the error log? Where could I find it?
    I can recommend using "trace", sample code here by Yours Truly

    Cheers,

    --jouni

  13. #13
    Nokia Developer Moderator
    Join Date
    May 2007
    Location
    21.46 N 72.11 E
    Posts
    3,800

    Re: Bluetooth comms - make event driven

    Quote Originally Posted by JOM View Post
    I can recommend using "trace", sample code here by Yours Truly

    Cheers,

    --jouni
    Aha, So we have one more debugging tool here

    Jouni, I would be nice if you add this to the Wiki article having Python Debugging Techniques,


    Best Regards,
    Croozeus
    Pankaj Nathani
    www.croozeus.com

  14. #14
    Super Contributor
    Join Date
    Mar 2003
    Location
    Espoo, Finland
    Posts
    976

    Re: Bluetooth comms - make event driven

    Quote Originally Posted by croozeus View Post
    Jouni, I would be nice if you add this to the Wiki article having Python Debugging Techniques
    I know, I know... but it's a bit more complicated system, not just fixed lines to copy & paste in certain fixed location.

    For example last night I was experimenting how to filter trace output, in order to keep the log file smaller and more useful. I should create a library, define API etc. However it was much more fun to write a new game

    But definitely it's on my to-do list!

    Cheers,

    --jouni in Budapest

Similar Threads

  1. How to make a bluetooth device work as master and slave at the same time?
    By luckyapplehead in forum Bluetooth Technology
    Replies: 4
    Last Post: 2010-09-17, 14:51
  2. Replies: 35
    Last Post: 2009-04-11, 14:36
  3. Debug launched file
    By robUx4 in forum Symbian Tools & SDKs
    Replies: 4
    Last Post: 2007-10-18, 12:23
  4. [Pys60, 3rd Ed.] build problems
    By MHOOO in forum Symbian
    Replies: 3
    Last Post: 2007-04-09, 19:00
  5. Possible to make Bluetooth link without JSR 82
    By Gerryo in forum Mobile Java Networking & Messaging & Security
    Replies: 8
    Last Post: 2006-09-12, 18:18

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×