def getBTTransport(self):
        if sys.platform == 'symbian_s60': 
            import btsocket
            sock=btsocket.socket(btsocket.AF_BT,btsocket.SOCK_STREAM)
            addr,services=btsocket.bt_discover()
            if len(services)>0:
                port = services[u'opencoin']
            else:
                port=services[services.keys()[0]]
            address=(addr,port)
            sock.connect(address)
        else:
            import bluetooth as bt
            #evil hack
            appuifw.note(u'Searching for devices','info')
            results = [r for r in bt.find_service() if r['name']==None]
            targets = []
            for result in results:
                targets.append(u'%s' % (bt.lookup_name(result['host'])))
            selected = appuifw.popup_menu(targets,u'Connect to...?')
            
            host = results[selected]['host']
            #port = results[selected]['port']
            port = 3
            print 'host: %s, port: %s' % (host,port)
            sock=bt.BluetoothSocket( bt.RFCOMM )
            sock.connect((host, port))

            



        return transports.BTTransport(sock)
Beispiel #2
0
 def connect(self):
     self.sock = btsocket.socket(btsocket.AF_BT, btsocket.SOCK_STREAM)
     btsocket.set_default_access_point(
         btsocket.access_point(btsocket.select_access_point()))
     addr, services = btsocket.bt_discover()
     print "Discovered: %s, %s" % (addr, services)
     if len(services) > 0:
         import appuifw
         choices = services.keys()
         choices.sort()
         choice = appuifw.popup_menu(
             [unicode(services[x]) + ": " + x for x in choices],
             u'Choose port:')
         port = services[choices[choice]]
     else:
         port = 1
     address = (addr, port)
     print "Connecting to " + str(address) + "...",
     self.sock.connect(address)
     #except socket.error, err:
     #    if err[0]==54: # "connection refused"
     #        if _s60_UI:
     #            appuifw.note(u'Connection refused.','error')
     #        else:
     #            print "Connection refused."
     #        return None
     #    raise
     print "OK."
Beispiel #3
0
    def connect(self):
        self.sock=btsocket.socket(btsocket.AF_BT,btsocket.SOCK_STREAM)
	btsocket.set_default_access_point(btsocket.access_point(btsocket.select_access_point()))
        addr,services=btsocket.bt_discover()
        print "Discovered: %s, %s"%(addr,services)
        if len(services)>0:
            import appuifw
            choices=services.keys()
            choices.sort()
            choice=appuifw.popup_menu([unicode(services[x])+": "+x
                                       for x in choices],u'Choose port:')
            port=services[choices[choice]]
        else:
            port=1
        address=(addr,port)
        print "Connecting to "+str(address)+"...",
        self.sock.connect(address)
        #except socket.error, err:
        #    if err[0]==54: # "connection refused"
        #        if _s60_UI:
        #            appuifw.note(u'Connection refused.','error')
        #        else:
        #            print "Connection refused."
        #        return None
        #    raise
        print "OK." 
def test_socket():
    """ Tests the btsocket module for selection of access point and displays
        the selected value. Also checks if a device can be selected to connect
        via bluetooth.

    """
    options = [u"discover", u"select_access_point"]
    menu_index = appuifw.popup_menu(options, u"Select")
    if menu_index == 0:
        btsocket.bt_discover()
    else:
        access_point_id = btsocket.select_access_point()
        for access_point in btsocket.access_points():
            if access_point['iapid'] == access_point_id:
                appuifw.note(u"The access point selected is: " + \
                unicode(access_point['name']))
                break
Beispiel #5
0
def chat_client():
    conn = btsocket.socket(btsocket.AF_BT, btsocket.SOCK_STREAM)
    address, services = btsocket.bt_discover()
    if 'btchat' in services:
        channel = services[u'btchat']
        conn.connect((address, channel))
        print "Connected to server!"
        talk(None, conn)
    else:
        appuifw.note(u"Target is not running a btchat server", "error")
def bt_povezi():
    global sock
    sock = btsocket.socket(btsocket.AF_BT, btsocket.SOCK_STREAM)
    target = ""
    address, services = btsocket.bt_discover()
    if len(services) > 1:
        import appuifw

        choices = services.keys()
        choices.sort()
        choice = appuifw.popup_menu([unicode(services[x]) + ": " + x for x in choices], u"Choose port:")
        target = (address, services[choices[choice]])
    else:
        target = (address, services.values()[0])
    print "Povezujem..." + str(target)
    sock.connect(target)
    print "OK."
Beispiel #7
0
 def bt_connect(self):
   try:
     target = ''
     (address, services) = btsocket.bt_discover()
     choices = services.keys()
     choices.sort()
     choice = appuifw.popup_menu([unicode(services[x]) + ": " + x for x in choices], u'Choose port:')
     target = (address, services[choices[choice]])
 
     self.sock = btsocket.socket(btsocket.AF_BT, btsocket.SOCK_STREAM)
     self.sock.connect(target)
     return True
   except:
     if self.sock:
       del self.sock
     appuifw.note(u'Failed to connect', 'error')
     return False
def connect(): #this function sets up the BT socket connection
    global btsocket, target

    try:
         #socket params passed to the OS
        btsocket=socket.socket(socket.AF_BT,socket.SOCK_STREAM)

        if target == '': #if no target defined, begin OS discovery routine
            address,services = socket.bt_discover()
            target = (address, services.values()[0])

        btsocket.connect(target) #initiate connection and notify user
        appuifw.note(u"Connected to " + str(address), "info")

    except: #fail cleanly
        appuifw.note(u"Error connecting to device")
        btsocket.close()
        for name, channel in services.items():
                names.append(name)
                channels.append(channel)
        index = appuifw.popup_menu(names, u"Choose service")
        return channels[index]

def read_and_echo(fd):
        buf = r = ""
        while r != "\n" and r != "\r":
                r = fd.read(1)
                if ECHO: fd.write(r)
                buf += r
        if ECHO: fd.write("\n")
        return buf

address, services = btsocket.bt_discover()
channel = choose_service(services)
conn = btsocket.socket(btsocket.AF_BT, btsocket.SOCK_STREAM)
conn.connect((address, channel))
to_peer = conn.makefile("rw", 0)

while True:
        msg = appuifw.query(u"Send a message", "text")
        if msg:
                print >> to_peer, msg + "\r"
                print "Sending: " + msg
                print "Waiting for reply..."
                reply = read_and_echo(to_peer).strip()
                appuifw.note(unicode(reply), "info")
                if reply.find("bye!") != -1:
                        break
Beispiel #10
0
def connect(address=None):
    """Form an RFCOMM socket connection to the given address. If
    address is not given or None, query the user where to connect. The
    user is given an option to save the discovered host address and
    port to a configuration file so that connection can be done
    without discovery in the future.

    Return value: opened Bluetooth socket or None if the user cancels
    the connection.
    """

    # Bluetooth connection
    sock = socket.socket(socket.AF_BT, socket.SOCK_STREAM)

    if not address:
        CONFIG_DIR = 'c:/system/apps/python'
        CONFIG_FILE = os.path.join(CONFIG_DIR, 'btconsole_conf.txt')
        try:
            f = open(CONFIG_FILE, 'rt')
            try:
                config = eval(f.read())
            finally:
                f.close()
        except:
            config = {}

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

        if address:
            if _s60_UI:
                choice = appuifw.popup_menu([u'Default host', u'Other...'],
                                            u'Connect to:')
                if choice == 1:
                    address = None
                if choice == None:
                    return None  # popup menu was cancelled.
            else:
                sel = raw_input("Connect to default host? y/n[y]:")
                if sel and 'y' != sel and 'Y' != sel:
                    address = None

        if not address:
            print "Discovering..."
            try:
                addr, services = socket.bt_discover()
            except socket.error, err:
                if err[0] == 2:  # "no such file or directory"
                    if _s60_UI:
                        appuifw.note(u'No serial ports found.', 'error')
                    else:
                        print "No serial ports found."
                elif err[0] == 4:  # "interrupted system call"
                    print "Cancelled by user."
                elif err[0] == 13:  # "permission denied"
                    print "Discovery failed: permission denied."
                else:
                    raise
                return None
            print "Discovered: %s, %s" % (addr, services)
            if len(services) > 1:
                choices = services.keys()
                choices.sort()
                if _s60_UI:
                    choice = appuifw.popup_menu(
                        [unicode(services[x]) + ": " + x for x in choices],
                        u'Choose port:')
                    port = services[choices[choice]]
                else:
                    index = 0
                    for item in choices:
                        print "%d -> %s" % (index, item)
                        index += 1
                    choice = raw_input("Choose port: ")
                    try:
                        port = services[choices[int(choice)]]
                    except:
                        print "Invalid input."
                        return None
            else:
                port = services[services.keys()[0]]
            address = (addr, port)
            if _s60_UI:
                choice = appuifw.query(u'Set as default?', 'query')
            else:
                choice = False
                sel = raw_input("Set as default? y/n[y]:")
                if not sel or 'y' == sel or 'Y' == sel:
                    choice = True

            if choice:
                config['default_target'] = address
                # make sure the configuration file exists.
                if not os.path.isdir(CONFIG_DIR):
                    os.makedirs(CONFIG_DIR)
                f = open(CONFIG_FILE, 'wt')
                f.write(repr(config))
                f.close()
Beispiel #11
0
def connect(address=None):
    """Form an RFCOMM socket connection to the given address. If
    address is not given or None, query the user where to connect. The
    user is given an option to save the discovered host address and
    port to a configuration file so that connection can be done
    without discovery in the future.

    Return value: opened Bluetooth socket or None if the user cancels
    the connection.
    """
    
    # Bluetooth connection
    sock=socket.socket(socket.AF_BT,socket.SOCK_STREAM)

    if not address:
        CONFIG_DIR='c:/system/apps/python'
        CONFIG_FILE=os.path.join(CONFIG_DIR,'btconsole_conf.txt')
        try:
            f=open(CONFIG_FILE,'rt')
            try:
                config=eval(f.read())
            finally:
                f.close()
        except:
            config={}
    
        address=config.get('default_target','')
    
        if address:
            if _s60_UI:
                choice=appuifw.popup_menu([u'Default host',
                                           u'Other...'],u'Connect to:')
                if choice==1:
                    address=None
                if choice==None:
                    return None # popup menu was cancelled.
            else:
                sel=raw_input("Connect to default host? y/n[y]:")
                if sel and 'y' != sel and 'Y' != sel:
                    address=None

        if not address:
            print "Discovering..."
            try:
                addr,services=socket.bt_discover()
            except socket.error, err:
                if err[0]==2: # "no such file or directory"
                    if _s60_UI:
                        appuifw.note(u'No serial ports found.','error')
                    else:
                        print "No serial ports found."
                elif err[0]==4: # "interrupted system call"
                    print "Cancelled by user."
                elif err[0]==13: # "permission denied"
                    print "Discovery failed: permission denied."
                else:
                    raise
                return None
            print "Discovered: %s, %s"%(addr,services)
            if len(services)>1:
                choices=services.keys()
                choices.sort()
                if _s60_UI:
                    choice=appuifw.popup_menu([unicode(services[x])+": "+x
                                           for x in choices],u'Choose port:')
                    port=services[choices[choice]]
                else:
                    index=0
                    for item in choices:
                        print "%d -> %s" %(index,item)
                        index+=1
                    choice=raw_input("Choose port: ")
                    try:
                        port=services[choices[int(choice)]]
                    except:
                        print "Invalid input."
                        return None
            else:
                port=services[services.keys()[0]]
            address=(addr,port)
            if _s60_UI:
                choice=appuifw.query(u'Set as default?','query')
            else:
                choice=False
                sel=raw_input("Set as default? y/n[y]:")
                if not sel or 'y' == sel or 'Y' == sel:
                    choice=True

            if choice:
                config['default_target']=address
                # make sure the configuration file exists.
                if not os.path.isdir(CONFIG_DIR):
                    os.makedirs(CONFIG_DIR)
                f=open(CONFIG_FILE,'wt')
                f.write(repr(config))
                f.close()