from bluetooth import *

import sys
import os

addr = None
rfnum = 1

if len(sys.argv) < 2:
    print "no device specified.  Searching all nearby bluetooth devices for the dialup service"
    devs = discover_devices(lookup_names=True)

    if not devs:
        print "no bluetooth devices found"
        sys.exit(1)

    if len(devs) == 1:
        addr = devs[0][0]

    else:
        for i in enumerate(devs):
            print str(i[0]+1)+")", i[1][0], i[1][1]

            while True:
                num = raw_input("Which device? ")
                try: 
                    num = int(num)
                except:
                    continue
        
            if num > 0 and num <= len(devs):
                break

        addr = devs[num-1][0]

else:
    addr = sys.argv[1]

print "Searching for dialup service on %s" % addr
matches = find_service( address = addr )

service_matches = filter (lambda s: DIALUP_NET_CLASS in s.get ("service-classes", []), \
                      matches)
if len(service_matches) == 0:
    print "couldn't find the dialup service =("
    sys.exit(0)

first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]
print "connecting to \"%s\" on %s" % (name, host)

udi="""access_control.file = '/dev/rfcommXYZ'  (string)
  access_control.type = 'modem'  (string)
  info.bus = 'virtual'  (string)
  info.callouts.add = {'hal-acl-tool --add-device'} (string list)
  info.callouts.remove = {'hal-acl-tool --remove-device'} (string list)
  info.capabilities = {'serial', 'access_control', 'modem', 'gsm'} (string list)
  info.category = 'serial'  (string)
  info.linux.driver = 'rfcomm'  (string)
  info.product = 'Bluetooth rfcomm'  (string)
  info.subsystem = 'rfcomm'  (string)
  info.udi = '/org/freedesktop/Hal/devices/virtual_rfcommXYZ' (string)
  linux.device_file = '/dev/rfcommXYZ'  (string)
  linux.subsystem = 'rfcomm'  (string)
  linux.sysfs_path = '/sys/devices/virtual/tty/rfcommXYZ'  (string)
  modem.command_sets = {'GSM-07.07'} (string list)
  serial.device = '/dev/rfcommXYZ'  (string)
  serial.originating_device = '/org/freedesktop/Hal/devices/virtual_rfcommXYZ'  (string)
  serial.type = 'bluetooth'  (string)
"""

udi = udi.replace("rfcommXYZ", "rfcomm%d" % rfnum)

# cleanup
os.system("rfcomm release /dev/rfcomm%d >/dev/null 2>/dev/null" % rfnum)
os.system('hal-device -r "/org/freedesktop/Hal/devices/virtual_rfcomm%d" >/dev/null 2>/dev/null' % rfnum)

# create
os.system("rfcomm bind /dev/rfcomm%d %s %s" % (rfnum, host, port))
(rfd, wfd) = os.popen2(['hal-device', '-a', '/org/freedesktop/Hal/devices/virtual_rfcomm%d' % rfnum])
rfd.write(udi)
rfd.close()
while wfd.readlines():
    pass
wfd.close()

