5 Replies - 1635 Views - Last Post: 24 May 2010 - 07:33 PM Rate Topic: *---- 1 Votes

#1 draike09  Icon User is offline

  • New D.I.C Head

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

Bluetooth Project Help

Posted 22 May 2010 - 07:43 PM

can someone help me in my project. it's about copying file in My documents<PC server> using mobile<mobile client> enable bluetooth.. but the objective is to view the files that the user want to copy. the files names can be viewed in the mobile.


or just having a text box then type on it the file names that you want to copy then click the button to copy. as long as we don't need to do anything in the server..client do all the job the server just accept connection and send data to the client..

i have created my client and server but the problem is that it copy all the files on the directory..my objective is to copy file one by one..

or if much better i can view the file names of the file i want to copy..
pls someone help me..

Is This A Good Question/Topic? 0
  • +

Replies To: Bluetooth Project Help

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6063
  • View blog
  • Posts: 23,515
  • Joined: 23-August 08

Re: Bluetooth Project Help

Posted 22 May 2010 - 08:43 PM

Are you trying to do thin in Python or Perl, or some other language? It's not very clear.
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: Bluetooth Project Help

Posted 23 May 2010 - 11:20 PM

im sorry.

im using phyton language..
Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6063
  • View blog
  • Posts: 23,515
  • Joined: 23-August 08

Re: Bluetooth Project Help

Posted 24 May 2010 - 06:00 AM

OK, so the next step here -- now that we've established that -- is for you to post your code, along with any errors you might have. Note that if you did that with your first post, together we could have saved ourselves four unnecessary posts.
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: Bluetooth Project Help

Posted 24 May 2010 - 07:25 PM

im sorry again...

heres my client code
import appuifw
import phcomm
import os
import sys
import glob
import key_codes
import e32
import dir_iter
from key_codes import EKeyLeftArrow

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"Rename"])
				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
						os.remove( item )
						entries = self.current_dir.list_repr()
						self.lb.set_list( entries, index-1 )
			
        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 ):
    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]
                if not os.path.exists( dirpath ):
                    os.makedirs( dirpath ) 
                open( ph_file, 'wb' ).write( self.recv_data() )
                print 'received', ph_file

                if with_reload:
                    # reload a module if it appears in sys.modules
                    modpath, ext = os.path.splitext( ph_file )
                    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
                        data = open( fname, 'rb' ).read()
                        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"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()
			
class LoginManager:
    def __init__(self):
        passwd = appuifw.query(u"Please enter password:", "code")
			
if __name__ == '__main__':
    UserLogin = LoginManager()
    main()
#else:
#    main( False ) # for faster debugging, use the default host



here is my server code..
#Main Server Class module
#Execution starts here

#Imports for needed libraries
import wx
import sqlite3
from bluetooth import *
import serial
import sys
import random

import images
import SyncDaemon

class DemoTaskBarIcon(wx.TaskBarIcon):
    TBMENU_RESTORE = wx.NewId()
    TBMENU_CLOSE   = wx.NewId()
    TBMENU_CHANGE  = wx.NewId()
    TBMENU_REMOVE  = wx.NewId()
    
    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)
        self.frame = frame
        icon = self.MakeIcon(images.WXPdemo.GetImage())
        self.SetIcon(icon, "BlueCopier")
        self.imgidx = 1
        
        # bind some events
        self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate)
        self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=self.TBMENU_RESTORE)
        self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE)
        self.Bind(wx.EVT_MENU, self.OnTaskBarChange, id=self.TBMENU_CHANGE)
        self.Bind(wx.EVT_MENU, self.OnTaskBarRemove, id=self.TBMENU_REMOVE)
        
    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(self.TBMENU_CLOSE,   "Close Bluetooth Server")
        return menu

    def MakeIcon(self, img):
        if "wxMSW" in wx.PlatformInfo:
            img = img.Scale(16, 16)
        elif "wxGTK" in wx.PlatformInfo:
            img = img.Scale(22, 22)
		
        # wxMac can be any size upto 128x128, so leave the source img alone....
        icon = wx.IconFromBitmap(img.ConvertToBitmap() )
        return icon
    

    def OnTaskBarActivate(self, evt):
        if self.frame.IsIconized():
            self.frame.Iconize(False)
        if not self.frame.IsShown():
            self.frame.Show(True)
        self.frame.Raise()

    def OnTaskBarClose(self, evt):
        self.RemoveIcon()
        self.frame.Close()
        wx.Close()
        sys.exit(0)


    def OnTaskBarChange(self, evt):
        names = [ "WXPdemo", "Mondrian", "Pencil", "Carrot" ]                  
        name = names[self.imgidx]
        
        eImg = getattr(images, name)
        self.imgidx += 1
        if self.imgidx >= len(names):
            self.imgidx = 0
            
        icon = self.MakeIcon(eImg.Image)
        self.SetIcon(icon, "This is a new icon: " + name)

    def OnTaskBarRemove(self, evt):
        self.RemoveIcon()

class TaskFrame(wx.Frame):
	def __init__(self):
		wx.Frame.__init__(self, None, -1, '', size=(250, 130), style = wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX))
		self.tbicon = DemoTaskBarIcon(self)
		self.Hide()
		self.BTServer = SyncDaemon.sync_server('sync.config').run()

class ServerApp(wx.App):
	def OnInit(self):
		self.Logger = TaskFrame()
		self.Logger.Hide()
		return True
	
	def __init__(self, redirect = True, filename = 'Server log.txt'):
		wx.App.__init__(self, redirect, filename)

'''
dlg = wx.MessageDialog(None, "Are you sure you want to exit?", 'Server', wx.YES_NO | wx.ICON_QUESTION)
		result = dlg.ShowModal()
		dlg.Destroy()
		if result == wx.ID_YES:
			self.severeConnections()
			self.Close()
'''
########################################################################################

class UserSentinel:
    def __init__(self):
        self.con = sqlite3.connect("../Database/users.db")
        self.cur = self.con.cursor()
        self.cur.execute('SELECT * FROM users')
		
    def AuthenticateUser(self):
        self.cur.execute("SELECT * FROM users WHERE username = '" + self.nameText.GetValue() + "' AND password = '" + self.pwdText.GetValue() + "'")
        self.row = self.cur.fetchone()
        if self.row:
            self.closeDatabase()
            self.Close()
            self.loadMainServer()
        else:
            wx.MessageBox("Invalid username / password, please try again", "User not found", wx.OK | wx.ICON_EXCLAMATION, self)
            self.nameText.SetValue("")
            self.pwdText.SetValue("")
		
    def closeDatabase(self):
        self.cur.close()
        self.con.close()
########################################################################################

if __name__ == "__main__":
	MainApp = ServerApp(redirect = True)
	MainApp.MainLoop()

this is part of the server phonecomm.py
"""
phcomm.py

Phone - PC communication module

Create a simple protocol where commands are newline-terminated strings,
not checked for correctness of transmission, and binary data is sent
preceded by a header that allows checking for transmission errors (with crc32).
"""

import os
import sys
import socket
import binascii
import marshal
import struct

def data_checksum( data ):
    return binascii.crc32( data )

def file_checksum( filename ):
    try: 
        return binascii.crc32( open( filename, 'rb' ).read() )
    except IOError, (errno, strerror):
        if errno != 2:
            # errno == 2 is the file doesn't exist, that's OK
            # other errors should be printed
            print 'IOError in file_checksum( %s ): %s' % (filename, strerror)
        return None

def file_checksums( filelist ):
    retval={}
    for fname in filelist:
        retval[ fname ] = file_checksum( fname )
    return retval

def discover_address( config_file, interactive = True ):
    """ discover_address( config_file, interactive = True )
    called on the phone side
    config_file stores the address and port of previous connection
    if interactive == False that address is used, otherwise
    the user is prompted to select device and service
    """
    import appuifw

    CONFIG_DIR  = 'c:/system/apps/python'
    CONFIG_FILE = os.path.join( CONFIG_DIR, config_file )
    try:        
        config = eval( open(CONFIG_FILE, 'r').read() )
    except:
        config = {}

    address = config.get( 'target', '' )

    if address and not interactive:
        return address

    if address:
        choice = appuifw.popup_menu( [u'Default host', u'Other...'],
                                     u'Connect to:' )
        if choice == 0:
            return address
        if choice == None:
            return None # popup menu was cancelled

    # address not stored, or want a new host
    print "Discovering..."
    addr, services = socket.bt_discover()
    print "Discovered: %s, %s" % ( addr, services )
    if len(services) > 1:
        choices = services.keys()
        choices.sort()
        def dropendzero(x):
            # this is to overcome a bug of choice strings
            # having a terminating zero...
            if ord(x[-1]) == 0:
                return unicode( x[:-1] )
            else:
                return unicode( x )
        #l = [(unicode(services[x]), dropendzero(x)) for x in choices]
        #choice  = appuifw.popup_menu( l, u'Choose port (scroll):' )
        l = [ dropendzero(x) for x in choices ]
        choice  = appuifw.popup_menu( l, u'Choose port:' )
        if choice == None:
            print 'no choice'
            return None
        port = services[choices[choice]]
    else:
        port = services.values()[0]
    address = ( addr, port )
    config['target'] = address
    # make sure the configuration file exists
    if not os.path.isdir( CONFIG_DIR ):
        os.makedirs( CONFIG_DIR )
    # store the configuration file
    open( CONFIG_FILE, 'wt' ).write( repr( config ) )
    return address


def connect_PC2phone( com_port, verbose=0 ):
    """com_port 1 == COM1, etc."""
    class filesocket:
        """Give a socket API to an object that otherwise has a file API
        """
        def __init__( self, file ):
            self.file = file
        def recv( self, n=1 ):
            return self.file.read( n )
        def send( self, msg ):
            self.file.write( msg )
            self.file.flush()
            return len( msg )
        def close( self ):
            pass
    try:
        import serial
        import types
        # pyserial module http://sourceforge.net/projects/pyserial/
        if type(com_port) == types.IntType:
            c_port = com_port - 1
        elif type(com_port) == types.StringType:
            c_port = com_port
        else:
            print "Wrong type of com_port in config file"
            sys.exit()
        try:
            ser = serial.Serial( c_port, timeout = 2 )
        except serial.serialutil.SerialException, e:
            print "Opening COM port failed (maybe it's already in use?)"
            print '    ', e
            sys.exit( 1 )
        print 'Connecting to serial port', ser.portstr
        return filesocket( ser )
    except ImportError:
        print 'need pyserial module'
        raise 


def connect_phone2PC( config_file, interactive = True ):
    addr = discover_address( config_file, interactive)
    if addr:
        s = socket.socket( socket.AF_BT, socket.SOCK_STREAM )
        #print "Connecting to "+`addr`
        s.connect( addr )
        #print "Connected to "+`addr`
        return s
    else:
        print 'Failed to connect.'
        return None


class SvrCli:
    """ base class for Server and Client
    """
    def log( self, s ):
        sys.stdout.write( s + '\n' )
        sys.stdout.flush()

    def check_timeout( self, secs = 5 ):
        rd = True
        try:
            # on the phone side, check for timeout
            import appuifw  # on PC this should fail, so no timeout check
            import select
            rd, wr_dummy, ex_dummy = select.select( [self.sock], [], [], secs )
        except:
            pass
        if rd == []:
            # workaround for the bug where select on phone keeps a pointer
            # in C++ when at timeout
            self.sock._sock.close()
            self.sock.close()
            self.sock = None
            raise 'Timeout'
        
    def recv_data( self ): 
        #self.log("Waiting for content length..."
        self.check_timeout( 3 )
#         s1, s2 = self.sock.recv(8), self.sock.recv(8)
#         #print 'recv', s1, s2
#         content_length, crc32 = hexstring2int( s1 ), hexstring2int( s2 )
#         #print content_length, crc32
        content_length, crc32 = tuple( [int(s) for s in self.readline().split()] )
        self.log("Content-Length: %d\n" % content_length)
        recvbytes      = 0
        content        = []
        #self.log("Receiving data...")
        while recvbytes < content_length:
            recvstring = self.sock.recv( min(content_length-recvbytes,2048) )
            recvbytes  += len(recvstring)
            self.log("Received: %d bytes (%3.1f%%)\r"%(recvbytes,(100.*recvbytes/content_length)))
            content.append( recvstring )
        self.log("Received: %d bytes.        "%(recvbytes)+"\n")
        content = ''.join(content)
        if crc32 != binascii.crc32(content):
            str = """\
            expected crc %d, calculated crc %d
            expected content length %d, content length %d
            """ % (crc32, binascii.crc32(content), content_length, len(content))
            raise IOError("CRC error while receiving data:\n"+str)
        return content
    
    def send_data( self, data ):
        self.log("Content-Length: %d\n" % len(data))
#         #print 'send', len(data), binascii.crc32(data)
#         #print int2hexstring(len(data)), int2hexstring(binascii.crc32(data)) 
#         self.sock.send( int2hexstring(len(data)) )
#         self.sock.send( int2hexstring(binascii.crc32(data)) )
        self.write( '%d %d\n' % (len(data), binascii.crc32(data) ) )
        sentbytes = 0        
        # Send the data in little bits because the Bluetooth serial
        # connection may lose data on large sends.
        MAX_SEND  = 2048
        while sentbytes < len(data):
            n = min( len(data)-sentbytes, MAX_SEND )
            self.write( data[sentbytes:sentbytes+n] )
            sentbytes += n
            self.log( "Sent: %d bytes (%3.1f%%)\r" % ( sentbytes, (100.*sentbytes/len(data)) ) )

    def send_pyobj( self, obj ):
        """ send a python object, e.g., a unicode string """
        self.log( 'sent ' + `obj` )
        self.send_data( marshal.dumps( obj ) )
        
    def recv_pyobj( self ):
        """ receive a python object, e.g., a unicode string """
        obj = marshal.loads( self.recv_data() )
        self.log( 'received ' + `obj` )
        return obj
        
    def send( self, cmd, data = '' ):
        """ send a command line, with optional binary data """
        cmd = cmd.strip() + '\n'
        self.log( cmd )
        self.write( cmd )
        if data:
            self.send_data( data )
            
    def readline( self ):
        s,c = [],''
        while c != '\n':
            c = self.sock.recv(1)
            #self.log( 'Got ' + c + '\n' )
            if c:
                s.append(c)
                #self.log( 'Buffer: ' + ''.join(s) )
        return ''.join(s)
    
    def write( self, msg ):
        self.sock.send(msg)


class Server( SvrCli ):
    """ code for server, extend this class in your application
    """
    def __init__( self, sock, verbose=0 ):
        self.sock    = sock
        if not verbose:
            self.log = lambda x:0

    def cmd_quit( self, line ):
        self.finished = True

    def cmd_invalid( self, line ):
        self.log( 'Invalid command ' + line )
        self.finished = True

    def cmd_exec( self, cmdline ):
        command = eval( self.recv_data() )
        self.log( "exec " + command )
        try:
            exec command in globals()
            result = ( 0, '' )
        except:
            import traceback
            result = ( 1, apply(traceback.format_exception, sys.exc_info()) )
        self.send_data( repr(result) )

    def cmd_eval( self, cmdline ):
        expr = eval( self.recv_data() )
        self.log( "eval " + expr )
        # two eval's because we need to first get rid of one level of quoting
        result = ''
        try:
            value = eval(expr,globals())
            result = ( 0, value )
        except:
            import traceback
            result = ( 1, apply(traceback.format_exception, sys.exc_info()) )
        self.send_data( repr(result) )

    def run(self):
        self.log( 'Running...' )
        self.finished = False
        while not self.finished:
            cmdline = self.readline().rstrip()
            #self.log("Received: "+cmdline)
            words = cmdline.split()
            if len(words):
                cmd = 'cmd_' + words[0]
                self.log( "Running command: " + cmdline )
                if not cmd in dir(self):
                    self.cmd_invalid( cmdline )
                else:
                    exec 'self.%s( cmdline )' % cmd
        try:
            # workaround for the bug where select on phone keeps a pointer
            # in C++ when at timeout
            self.sock._sock.close()
        except:
            pass
        self.sock.close()

            
class Client( SvrCli ):
    """ code for client, extend this in your application
    """
    def __init__( self, sock, verbose=0 ):
        self.sock    = sock
        if not verbose:
            self.log = lambda x:0

    def sendexpr( self, cmd, expr ):
        self.send( '%s %s\n' % (cmd, expr), repr(expr) )
        result = eval( self.recv_data() )
        if result[0]!=0:
            raise "Exception on server side: " + ''.join(result[1])
        else:
            return result[1]
        
    def execute( self, expr ):
        self.sendexpr( 'exec', expr )

    def evaluate( self, expr ):
        return self.sendexpr( 'eval', expr )
        
    def killserver( self ):
        self.send( 'quit' )

    def readline( self ):
        try:
            # on the phone side, check for timeout
            import appuifw  # on PC this fails, so no timeout check
            import select
            timeout = 10 # seconds
            rd, wr_dummy, ex_dummy = select.select( [self.sock], [], [], timeout )
            while rd == []:
                if appuifw.query( u'Timeout on BT, exit?', 'query' ):
                    self.killserver()
                    # workaround for the bug where select on phone keeps a pointer
                    # in C++ when at timeout
                    self.sock._sock.close()
                    self.sock.close()
                    self.sock = None 
                    raise Exception
                rd, wr_dummy, ex_dummy = select.select( [self.sock], [], [], timeout )
        except:
            pass
        return SvrCli.readline( self )


another 1 part of server.. SyncDaemon.py
#!/usr/bin/env python

import os,sys
import glob

# assuming phcomm is in ../libs relative to this file, now import finds it
# even if that directory is not in environment variable PYTHONPATH
sys.path.append( os.path.join( os.path.split(__file__)[0], '../libs' ) )
import PhoneComm as phcomm

class sync_server( phcomm.Server ):

    def __init__( self, config_file, verbose=0 ):
        # read in the config file
        # it should create variables COM_PORT and SYNC_FILES
        d = {}
        execfile( config_file, {}, d )
        # chdir to the directory of the config_file (if not already there)
        # so relative paths work
        try:
            os.chdir( os.path.split( config_file )[0] )
        except:
            pass
        self.sync_files = d['SYNC_FROM_PC']
        self.download_files = d['SYNC_TO_PC']
        # connect to phone
        sock = phcomm.connect_PC2phone( com_port=d['COM_PORT'], verbose=verbose )
        # initialize parent class
        phcomm.Server.__init__( self, sock, verbose )

    def cmd_msg( self, line ):
        print line.split( ' ', 1)[1]

    def cmd_sync( self, line ):
        # create lists of local and corresponding remote files and checksums
        remotefiles, localfiles, checksums = [], [], []
        for dest, srcs in self.sync_files:
            # for each destination directory there can be several
            # source directories
            dpath = os.path.normpath( dest )
            if not isinstance(srcs, tuple) and not isinstance(srcs, list):
                # force sources to list
                srcs = [ srcs ]
            for src in srcs:
                # for each source location
                for f in glob.glob( src ):
                    # find matching files
                    file = os.path.split(f)[1]
                    # create remote name, local name, checksum
                    remotefiles.append( os.path.join( dpath, file ) )
                    localfiles.append( os.path.normpath( f ) )
                    checksums.append( phcomm.file_checksum( f ) )

        #print 'send upload files', repr(zip(remotefiles, localfiles, checksums))
        # send to phone a list of remote, local, checksum triplets
        self.send_data( repr(zip(remotefiles, localfiles, checksums)) )

        #print 'send download files', repr( self.download_files )
        # then send the info about the files that you want to download to pc
        self.send_data( repr( self.download_files ) )
        
        print

    def cmd_getfile( self, line ):
        """the phone asks to get a file"""
        print 'cmd_getfile'
        filename = self.recv_data()
        self.send_data( open( filename, 'rb' ).read() )
        print 'sent file:', filename

    def cmd_sendfile( self, line ):
        """the phone sends a file"""
        filename = self.recv_data()
        print filename
        open( filename, 'wb' ).write( self.recv_data() )
        print 'received file:', filename

    def cmd_offerfile( self, line ):
        """the phone offers a filename and checksum, if that file with
        matching checksum exists, don't bother with it, otherwise get it"""
        filename = self.recv_data()
        crc = int( line.split()[1] )
        pc_crc = phcomm.file_checksum( filename )
        #print filename, crc, pc_crc
        if crc == pc_crc:
            # don't need this file
            self.send( '0' )
            #print 'skipping existing file', filename
        else:
            self.send( '1' )
            # create directory if needed
            dirpath = os.path.split( filename )[0]
            if not os.path.exists( dirpath ):
                os.makedirs( dirpath )
            # read and write the file
            open( filename, 'wb' ).write( self.recv_data() )
            print 'received file:', filename

if __name__ == '__main__':

    if len(sys.argv) < 2:
        print "usage: syncd.py <configfile>"
        print """

    convenience tool to bypass the upload-install-run cycle.
    configfile specifies which files you want uploaded to the phone.
    Run the sync.py on the phone, connect to the PC running syncd, and
    the phone will automatically download the files.
"""
    #sync_server( sys.argv[1], verbose=True ).run()
    print 'starting sync demon'
    sync_server( sys.argv[1] ).run()


Was This Post Helpful? 0
  • +
  • -

#6 draike09  Icon User is offline

  • New D.I.C Head

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

Re: Bluetooth Project Help

Posted 24 May 2010 - 07:33 PM

the code can copy files but the problem is it copies all of the files in a directory.. i want to view files of My document in my mobile..
or if not i can copy file one by one..like searching its file names and copy it..and oh..it's directory is not My Documents..i don't know on how to access My Documents
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1