5 Replies - 1330 Views - Last Post: 08 July 2010 - 06:56 AM Rate Topic: -----

#1 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

how do i close my Client's Bluetooth Connection to stop copying fi

Posted 07 July 2010 - 02:21 AM

here is my Client code.. can some one help me on closing my bluetooth conncetion
all i want is to close the Bluetooth connection when i return to the main menu..thank you


import appuifw
appuifw.app.title  = u'Bluetooth-Mobile FIle Copier'
appuifw.note(u"Starting Bluetooth-Mobile File Copier",'info')

import phcomm
import os
import sys
import glob
import key_codes
import e32
import dir_iter
import shutil
system_password = u"test"
l = []
#dir1 = "e:\\BlueCopier"
dir2 = "e:\\"
from key_codes import EKeyLeftArrow
global string
class Filebrowser:
	
    def __init__(self):
        self.script_lock = e32.Ao_lock()
        self.dir_stack = []
        self.current_dir = dir_iter.Directory_iter(e32.drive_list())

    def run(self):
        entries = self.current_dir.list_repr()
        if not self.current_dir.at_root:
            entries.insert(0, (u"..", u""))
        self.lb = appuifw.Listbox(entries, self.lbox_observe)
        self.lb.bind(EKeyLeftArrow, lambda: self.lbox_observe(0))
        old_title = appuifw.app.title
        self.refresh()
        self.script_lock.wait()
        appuifw.app.title = old_title
        appuifw.app.body = None
        self.lb = None

    def refresh(self):
        appuifw.app.title = u"File Browser"
        appuifw.app.menu = []
        appuifw.app.exit_key_handler = self.exit_key_handler
        appuifw.app.body = self.lb

    def do_exit(self):
        self.exit_key_handler()

    def exit_key_handler(self):
        appuifw.app.exit_key_handler = None
        self.script_lock.signal()

	
		
    def lbox_observe(self, ind = None):
	
        if not ind == None:
            index = ind
        else:
            index = self.lb.current()
        focused_item = 0

        if self.current_dir.at_root:
            self.dir_stack.append(index)
            self.current_dir.add(index)
        elif index == 0:                              # ".." selected
            focused_item = self.dir_stack.pop()
            self.current_dir.pop()
        elif os.path.isdir(self.current_dir.entry(index-1)):
            self.dir_stack.append(index)
            self.current_dir.add(index-1)
        else:
			self.item = self.current_dir.entry(index-1)
			if os.path.splitext(self.item)[1]:
				i = appuifw.popup_menu([u"Open", u"Delete",u"New Folder"])
				
				if i == 0:
					if os.path.splitext(self.item)[1].lower() == u'.py':
						execfile(self.item, globals())
						self.refresh()
					else:
						try:
							appuifw.Content_handler().open(self.item)
						except:
							import sys
							type, value = sys.exc_info() [:2]
							appuifw.note(unicode(str(type)+'\n'+str(value)), "info")
					return
				elif i == 1:
					index = self.lb.current()
					if self.current_dir.path == u'\\' or index == 0:
						# at system root or '..', can't delete those
						return
					item = self.current_dir.entry( index-1 )
					if os.path.isdir( item ):
						# currently can't delete directory
						return
					else:
						# a file, delete it
						if appuifw.query(u"Delete?",'query')  == True:
							os.remove( item )
							entries = self.current_dir.list_repr()
							self.lb.set_list( entries, index-1 )
							appuifw.note(u"File Deleted!", 'conf')
						else: 
							appuifw.note(u"Canceled!",'error')
							return
				elif i == 2:
					#appuifw.query(u"New Folder",'text')
					os.mkdir('NewFolder')
					#os.mkdir('e:\\BlueCopier')
					osmakdir('e:\\Bluecopier\\NewFolder')
					appuifw.note(u"Folder Created!",'conf')
					
				
        entries = self.current_dir.list_repr()
        if not self.current_dir.at_root:
            entries.insert(0, (u"..", u""))
        self.lb.set_list(entries, focused_item)
		
		
  	
			
				
  
class sync_client( phcomm.Client ):
    #pc_offering = 'C:\\Users\\Satellite\\Documents'
    def __init__( self, sock, verbose=0 ):
        phcomm.Client.__init__( self, sock, verbose )
                            
    def run( self, with_reload = False ):
        old_title  = appuifw.app.title
        appuifw.app.title  = u'Sync files'

        # change current directory to Python home
        cwd = os.getcwd()
        if os.path.exists( 'c:/system/apps/python/python.app' ):
            os.chdir( 'c:/system/apps/python' )
        elif os.path.exists( 'e:/system/apps/python/python.app' ):
            os.chdir( 'e:/system/apps/python' )

        # ask for file names, checksums
        self.send( 'sync' )
        try:
            pc_offering = eval(self.recv_data())
        except 'Timeout':
            print 'BT connection timed out.'
            print 'Are you sure sync demon is running on PC?'
            return
        pc_demand   = eval(self.recv_data())
        # check whether some of the files should be retrieved
        for ph_file, pc_file, checksum in pc_offering:
            #print ph_file, pc_file

            if checksum != phcomm.file_checksum( ph_file ):
                # checksums differ, get the file
                
                self.send( 'getfile', pc_file )
                # create / overwrite the file
                dirpath = os.path.split( ph_file )[0]
                
                print pc_offering
                dirpath = os.path.split( ph_file )[0]
                files=map(unicode,os.listdir(dirpath))
                index=appuifw.selection_list(files, search_field=1)
                select = appuifw.popup_menu([u"Menu",u"Copy Files"])
                if select == 0:

				<here is were want to put the syntax that close my BLuetooth connection>

                                        main() 
                elif select ==1:
					appuifw.note(u"Copying....[%s]!"% pc_file, 'info')
                if not os.path.exists( dirpath ):
                    os.makedirs( dirpath )					
                open( ph_file, 'wb' ).write( self.recv_data() )
                
                print 'Copied', ph_file
                appuifw.note(u"[%s] Copying Complete!"% pc_file, 'conf')
		
                if with_reload:
                    # reload a module if it appears in sys.modules
                    modpath, ext = os.path.splitext( ph_file )
                #    modpath, ext = os.path.spittext( pc_offering )
                    modname = os.path.split(modpath)[1].lower()
                    
                    if modname in sys.modules.keys():
                        reload( sys.modules[modname] )
                        print 'reloaded module: ', modname
            #else:
            #    print phcomm.file_checksum( ph_file ), checksum
       #print 'demand', pc_demand
        for targetdir, phone_patterns in pc_demand:
            if not isinstance(phone_patterns, tuple) and not isinstance(phone_patterns, list):
                # force patterns to be a list
                phone_patterns = [ phone_patterns ]
            for patt in phone_patterns:
                for fname in glob.glob( patt ):
					try:
                        # assume if reading works, the rest works too
						f = open( fname, 'rb' )
						data = f.read()
						f.close()
						
						crc = phcomm.data_checksum( data )
						print 'offering', fname
						self.send( 'offerfile %d' % crc )
						self.send_data( os.path.join(targetdir, os.path.split(fname)[1]) )
						if int(self.readline()):
							self.send_data( data )
							print '         SENT.'
						else:
							print '         NOT sent.'
					except:
						pass
		self.send( 'msg sync done.' )
		os.chdir( cwd )
		appuifw.app.title   = old_title
        
            
def main( interactive = True, with_reload = False ):
	

	index = appuifw.popup_menu([u"Copy Files", u"Browse Files",u"About",u"Exit"], u"Menu")

	if index != None:
		if index == 0:
			sock = phcomm.connect_phone2PC( 'sync_conf.txt', interactive )
			if sock:
				try:
					#sync_client( sock, verbose=True ).run()
					sync_client( sock ).run( with_reload )
					
				except:
					print 'sync_client run failed'
					import traceback
					traceback.print_exc()
					print "Sync done."
			else:
				print 'Did not connect, exiting.'
		elif index == 1:
			fileTrans = Filebrowser()
			fileTrans.run()
		elif index == 2:
			old_title  = appuifw.app.title
			appuifw.app.title  = u'About'
			fields = [(u"Title:",'text',u"Bluetooth-"),
					 (u"",'text', u"Mobile File"),
					 (u"",'text', u"Copier(v1.0)"),
					 (u"Developer:",'text', u"Marlon Nidua"),
					 (u"",'text',u"Richie Polo"),
					 (u"Licenced to:",'text',u"Bicol"),
					 (u"",'text',u"University"),
					 (u"",'text',u"College of"),
					 (u"",'text',u"Science"),
					 (u"",'text',u"Legazpi City")]
                        myForm = appuifw.Form(fields, flags=appuifw.FFormViewModeOnly)
                        myForm.execute()
		elif index == 3:
		    if appuifw.query(u"Exit?",'query')  == True:
				sys.exit()
			
		else: 
				appuifw.note(u"Canceled!",'error')
				return
class LoginManager:
    def __init__(self):
        passwd = appuifw.query(u"Please enter password:", "code")
        if passwd == system_password:
			main()
        else:
		appuifw.note(u"Wrong Password!","error")
		LoginManager()

if __name__ == '__main__':
    UserLogin = LoginManager()
    main()
#else:
#    main( False ) # for faster debugging, use the default host


This post has been edited by draike09: 07 July 2010 - 02:24 AM


Is This A Good Question/Topic? 0
  • +

Replies To: how do i close my Client's Bluetooth Connection to stop copying fi

#2 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 450
  • View blog
  • Posts: 795
  • Joined: 08-June 10

Re: how do i close my Client's Bluetooth Connection to stop copying fi

Posted 07 July 2010 - 05:33 AM

Debugging mobile phones is really hard...especially when you don't have the phone you're trying to debug!

A couple of suggestions:
  • Did you try self.close()?
  • Have you done a dir(phcomm.Client) to see what methods exist?


Usually third party modules come with documentation, I would surmise that the phcomm module has the capability to do this in that Client class.

This post has been edited by Motoma: 07 July 2010 - 05:33 AM

Was This Post Helpful? 0
  • +
  • -

#3 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

Re: how do i close my Client's Bluetooth Connection to stop copying fi

Posted 07 July 2010 - 06:44 AM

sir i know the phcomm module but i donnt know how to use it so that i can close the conncetion of my client from my server....
Was This Post Helpful? -1
  • +
  • -

#4 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 450
  • View blog
  • Posts: 795
  • Joined: 08-June 10

Re: how do i close my Client's Bluetooth Connection to stop copying fi

Posted 07 July 2010 - 07:25 AM

As I mentioned before, you will want to check the documentation.

If you did so, you would see that the Client class has a member function--aptly titled--killserver.

In your code, where you say "<here is were want to put the syntax that close my BLuetooth connection>" you should put in self.killserver().
Was This Post Helpful? 0
  • +
  • -

#5 draike09  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 19
  • Joined: 21-May 10

Re: how do i close my Client's Bluetooth Connection to stop copying fi

Posted 07 July 2010 - 10:41 AM

sir i tried putting the code self.killserver in my code, but it didnt work..
it continue to copy files even when i return to main menu.. i want to stop the bluettooh conncetion
when i return to main.so that it will not have an error when i connect again.
Was This Post Helpful? 0
  • +
  • -

#6 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 450
  • View blog
  • Posts: 795
  • Joined: 08-June 10

Re: how do i close my Client's Bluetooth Connection to stop copying fi

Posted 08 July 2010 - 06:56 AM

View Postdraike09, on 07 July 2010 - 11:41 AM, said:

sir i tried putting the code self.killserver in my code, but it didnt work..
it continue to copy files even when i return to main menu.. i want to stop the bluettooh conncetion
when i return to main.so that it will not have an error when i connect again.


The only suggestion I can give is to return instead of calling main(), add a finally statement after your try-except statement in main(), in which you delete your sock variable. Then wrap the whole main() function in a while loop.

Sorry I couldn't be more help.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1