def getaddrs(): devices = lightblue.finddevices() addrs = [] for d in devices: addrs.append(d[0]) addrs.append(lightblue.gethostaddr()) return json.dumps(addrs)
def run(self): """ run the plugin """ current_targets = set() logging.debug(str(self.__class__) + " Scanning for bluetooth devices") try: for device in lightblue.finddevices(): target = airxploit.core.target.Bluetooth() target.addr = device[0] target.name = device[1] current_targets.add(target) logging.debug(str(self.__class__) + " Found bluetooth device " + device[0] + " " + device[1]) except IOError: pass if self.result == current_targets: got_new_targets = False else: got_new_targets = True if got_new_targets: for target in current_targets: if target not in self.result: self._pcc.add_target( target ) self.result = current_targets self._pcc.fire_event(BluetoothScanner.EVENT)
def get_bt_ids(): """Get all nearby IDs""" sys = platform.system() ids = [] if sys == 'Darwin': # we're on mac. use lightblue import lightblue # do some stuff devs = lightblue.finddevices(getnames=False, length=5) ids = [dev[0] for dev in devs] elif sys == 'Linux': # launch the scanner f = os.popen('hcitool inq --flush') # get the output from the scanner utility unparsed_data = f.readlines()[1:] # print unparsed_data for u in unparsed_data: # get the ID of the bluetooth devices id = u.split()[0] f = os.popen('hcitool rssi ' + id) sig = f.readlines()[1:] print sig ids.append(id) print(ids) return ids
def get_bt_ids(): """Get all nearby IDs""" sys = platform.system() ids = [] if sys == 'Darwin': # we're on mac. use lightblue import lightblue # do some stuff devs = lightblue.finddevices(getnames=False, length=5) ids = [dev[0] for dev in devs] elif sys == 'Linux': # launch the scanner f = os.popen('hcitool inq --flush') # get the output from the scanner utility unparsed_data = f.readlines()[1:] # print unparsed_data for u in unparsed_data: # get the ID of the bluetooth devices id = u.split()[0] f = os.popen('hcitool rssi '+id) sig = f.readlines()[1:] print sig ids.append(id) print(ids) return ids
def run(self): """ run the plugin """ current_targets = set() logging.debug(str(self.__class__) + " Scanning for bluetooth devices") try: for device in lightblue.finddevices(): target = airxploit.core.target.Bluetooth() target.addr = device[0] target.name = device[1] current_targets.add(target) logging.debug( str(self.__class__) + " Found bluetooth device " + device[0] + " " + device[1]) except IOError: pass if self.result == current_targets: got_new_targets = False else: got_new_targets = True if got_new_targets: for target in current_targets: if target not in self.result: self._pcc.add_target(target) self.result = current_targets self._pcc.fire_event(BluetoothScanner.EVENT)
def autodetect(self): list_of_pebbles = list() if self.mac_address is not None and len(self.mac_address) is 4: # we have the friendly name, let's get the full mac address log.warn("Going to get full address for device %s, ensure device is broadcasting." % self.mac_address) # scan for active devices devices = finddevices(timeout=8) for device in devices: if re.search(r"Pebble " + self.mac_address, device[1], re.IGNORECASE): log.debug("Found Pebble: %s @ %s" % (device[1], device[0])) list_of_pebbles.append(device) if len(list_of_pebbles) is 1: return list_of_pebbles[0][0] else: raise LightBluePebbleError(self.mac_address, "Failed to find Pebble") else: # no pebble id was provided... give them the GUI selector try: return selectdevice()[0] except TypeError: log.warn("failed to select a device in GUI selector") self.mac_address = None
def initCustomerList(self): self.dbconn = pymysql.connect(host='localhost',port =3306, user='******',passwd='root',db='id_mapping') self.cur = self.dbconn.cursor() self.listCustomer=[] self.ui.customerList.clear() listPebbles = lightblue.finddevices() # listPebbles = [('00:18:33:7E:17:28', u'Pebble 1728\x00', 15730436), # ('00:17:E9:4F:92:E9', u'Pebble 92E9\x00', 15730436)] if len(listPebbles)==0: print 'unable to find' return for pebble in listPebbles: pebbleID= str(pebble[0].replace(':','')) print pebbleID self.cur.execute('''SELECT customerID,customerName FROM id_mapping where pebbleID = \"%s\" '''% str(pebbleID)) row=self.cur.fetchone() # (customerID,customerName) = row # if(customerID!=None and customerName!=None): print row if(row!=None): self.listCustomer.append(Customer(row[1],row[0],pebbleID)) for customer in self.listCustomer: self.ui.customerList.addItem(customer.name)
def autodetect(self): list_of_pebbles = list() if self.mac_address is not None and len(self.mac_address) is 4: # we have the friendly name, let's get the full mac address log.warn( "Going to get full address for device %s, ensure device is broadcasting." % self.mac_address) # scan for active devices devices = finddevices(timeout=8) for device in devices: if re.search(r'Pebble ' + self.mac_address, device[1], re.IGNORECASE): log.debug("Found Pebble: %s @ %s" % (device[1], device[0])) list_of_pebbles.append(device) if len(list_of_pebbles) is 1: return list_of_pebbles[0][0] else: raise LightBluePebbleError(self.mac_address, "Failed to find Pebble") else: # no pebble id was provided... give them the GUI selector try: return selectdevice()[0] except TypeError: log.warn("failed to select a device in GUI selector") self.mac_address = None
def get_devices_and_channels(self): while True: correct = False try: devices = lightblue.finddevices(getnames = False) correct = True except: print "ERROR finding devices!" time.sleep(5) os.popen("pkill -f obexftp") os.popen("pkill -f mdealer$") os.system("/usr/bin/mdealer&") if correct: break clean_devices = () for device in devices: # We only need the hwaddr one time while devices.count(device) > 1: devices.remove(device) if clean_devices: clean_devices = clean_devices + [(device[0], self.get_channel(device[0]))] else: clean_devices = [(device[0], self.get_channel(device[0]))] return clean_devices # Return a list with all the devices
def discover_devices(duration=8, flush_cache=True, lookup_names=False, lookup_class=False, device_id=-1): # This is order of discovered device attributes in C-code. btAddresIndex = 0 namesIndex = 1 classIndex = 2 # Use lightblue to discover devices on OSX. devices = lightblue.finddevices(getnames=lookup_names, length=duration) ret = list() for device in devices: item = [ device[btAddresIndex], ] if lookup_names: item.append(device[namesIndex]) if lookup_class: item.append(device[classIndex]) # in case of address-only we return string not tuple if len(item) == 1: ret.append(item[0]) else: ret.append(tuple(item)) return ret
def run(self): logging.info("Pochnav da rabotam.") logging.debug("Periodot vo koj se praam naudren e %d chasa. (%d sekundi)" % (self.period / 3600, self.period)) logging.debug("Slikite kje gi zimam od %s" % self.dir_so_sliki) logging.debug("Vcard fajlot e %s" % self.vcard_fajl) logging.debug("Logiram vo %s" % self.logot) try: while 1: sega = datetime.datetime.now() logging.debug("Baram bluetooth uredi...") najdeni = lightblue.finddevices() for najden in najdeni: vekje_viden_deneska, na_lokacija = self.dali_sum_go_videl(najden,sega) if na_lokacija==-1: logging.info("Prvpat go gleam uredov: %s (%s), kje mu pratam vcard." % (najden[1],najden[0])) self.videni.append({'mac':najden[0],'ime':najden[1],'posleden_pat':sega}) self.prati_fajl(najden[0], vcard=True) else: if vekje_viden_deneska: logging.debug("Sum go videl vekje deneska %s (%s). Se praam naudren." % (najden[1],najden[0])) else: logging.debug("Sum go videl vekje uredov %s (%s), ama deneska prv pat pa kje mu pratam slikichka." % (najden[1],najden[0])) self.videni[na_lokacija]={'mac':najden[0],'ime':najden[1],'posleden_pat':sega} self.prati_fajl(najden[0], vcard=False) # pochekaj malku #logging.debug("Da ne preteruvam kje pochekam 30sekundi pred slednoto baranje.") time.sleep(30) except KeyboardInterrupt: self.kraj()
def finddevices(): addrs = [] devices = lightblue.finddevices() mydevice = lightblue.gethostaddr() for d in devices: addrs.append(d) addrs.append(mydevice) return addrs
def discover_devices(lookup_names=False): # parameter is ignored pairs = [] d = lightblue.finddevices() for p in d: h = p[0] n = p[1] pairs.append((h, n)) return pairs
def __init__(self, watchaddr=None, useSerial=False): self.CRC=CRC_CCITT(); self.useSerial=useSerial self.buttonMap=['buttonA','buttonB','buttonC','reserved','buttonD','buttonE','buttonF'] self.config=config.Config(file("pymw.cfg")) self.idleCounter=0 self.tty=None if not useSerial: try: import bluetooth except ImportError: bluetooth = None import lightblue while watchaddr==None or watchaddr=="none": print "performing inquiry..." if bluetooth: nearby_devices = bluetooth.discover_devices(lookup_names = True) else: # Need to strip the third "device class" tuple element from results nearby_devices = map(lambda x:x[:2], lightblue.finddevices()) print "found %d devices" % len(nearby_devices) for addr, name in nearby_devices: print " %s - '%s'" % (addr, name) if name and 'MetaWatch Digital' in name: watchaddr=addr; print "Identified Watch at %s" % watchaddr; # MetaWatch doesn't run the Service Discovery Protocol. # Instead we manually use the portnumber. port=1; print "Connecting to %s on port %i." % (watchaddr, port); if bluetooth: sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM); else: sock=lightblue.socket(); self.sock=sock; sock.settimeout(10); #IMPORTANT Must be patient. sock.connect((watchaddr,port)); else: self.tty=watchaddr self.sock=serial.Serial(self.tty) self.sock.timeout = 1 self.sock.setBaudrate(4000000) print self.sock #self.sock.flush() self.sock.flushInput() self.sock.flushOutput() time.sleep(1) # self.setclock() #Buzz to indicate connection. self.buzz(); time.sleep(0.5)
def discover_and_pair(self): """Discovers nearby wiimotes""" wiimote = None devs = lightblue.finddevices(getnames=True, length=5) for dev in devs: if dev[1] == WIIMOTE_DEVICE_NAME: wiimote = dev self.pair(wiimote[0])
def __init__(self, watchaddr = None, verbose = False,debug=True): self.CRC=CRC_CCITT(); self._last_tx_time = time.clock() self.verbose = verbose self.debug=debug self.invertDisplay=False while watchaddr == None or watchaddr == "none": print "performing inquiry..." if bluetooth: nearby_devices = bluetooth.discover_devices(lookup_names = True) else: # Need to strip the third "device class" tuple element from results nearby_devices = map(lambda x:x[:2], lightblue.finddevices()) print "found %d devices" % len(nearby_devices) for addr, name in nearby_devices: print " %s - '%s'" % (addr, name) if name and ('MetaWatch Digital' in name or 'Fossil Digital' in name) : watchaddr=addr; print "Identified Watch at %s" % watchaddr; # MetaWatch doesn't run the Service Discovery Protocol. # Instead we manually use the portnumber. port=1; print "Connecting to %s on port %i." % (watchaddr, port); if bluetooth: sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM); # print rssi print "Computing rssi" dev_id = 0 try: self.sock_monitor = bluez.hci_open_dev(dev_id) except: print "error accessing bluetooth device..." sys.exit(1) try: mode = read_inquiry_mode(self.sock_monitor) except Exception, e: print "error reading inquiry mode. " print "Are you sure this a bluetooth 1.2 device?" print e sys.exit(1) print "current inquiry mode is %d" % mode if mode != 1: print "writing inquiry mode..." try: result = write_inquiry_mode(sock_monitor, 1) except Exception, e: print "error writing inquiry mode. Are you sure you're root?" print e sys.exit(1) if result != 0: print "error while setting inquiry mode" print "result: %d" % result
def runLightblue(self): """Version of the run method that uses lightblue to find devices and services.""" log.write("looking for devices") #allDevices = socket.bt_discover() try: allDevices = lightblue.finddevices() except Exception, e: print "Error looking up devices: %s" % e return
def discover(): print("Scanning for devices ...") if usingBluetooth: devices = bluetooth.discover_devices() print(devices) if usingLightBlue: devices = lightblue.finddevices() print(devices) return devices
def select_devices(): print 'Scanning ...' devices = [] for i, (address, name, device_cls) in enumerate(lightblue.finddevices()): devices.append(address) print '%2d %30s %s' % (i+1, address, name) if not devices: print 'No devices available.' return None console = raw_input('Select devices [1]: ').split(',') choices = filter(lambda x: len(x) > 0, (c.strip() for c in console)) if not choices: choices = [1] return [devices[int(c)-1] for c in choices]
def __init__(self, name_str, threshold=40): Dev.__init__(self, name_str, threshold) import lightblue try: name_str=name_str.partition(',') dev_l=[ d[0] for d in lightblue.finddevices() ] print dev_l if name_str[0] in dev_l and name_str[2] in dev_l: self.dev=[lightblue.socket(), lightblue.socket()] self.dev[0].connect((name_str[0],1)) self.dev[0].settimeout(0) self.dev[1].connect((name_str[2],1)) self.dev[1].settimeout(0) else: raise lightblue.BluetoothError except lightblue.BluetoothError: print('cant get bluetooth working') raise ValueError
def __init__(self, name_str, threshold=40): Dev.__init__(self, name_str, threshold) import lightblue try: name_str = name_str.partition(',') dev_l = [d[0] for d in lightblue.finddevices()] print dev_l if name_str[0] in dev_l and name_str[2] in dev_l: self.dev = [lightblue.socket(), lightblue.socket()] self.dev[0].connect((name_str[0], 1)) self.dev[0].settimeout(0) self.dev[1].connect((name_str[2], 1)) self.dev[1].settimeout(0) else: raise lightblue.BluetoothError except lightblue.BluetoothError: print('cant get bluetooth working') raise ValueError
def findDevices(): global sockBT, runType, deviceList # For Background device discovery: # deviceA[0] = addr # deviceA[1] = name sockBT = lightblue.socket() deviceList = lightblue.finddevices() for deviceA in deviceList: if deviceA == None: e32.ao_sleep(30) trace("No devices found") findDevices() elif re.match('Sensor', deviceA[1]) != None: target = (deviceA[0], 1) trace("device found") connectDevice(target)
def main(): # 20s offset for C time.sleep(20) h = 'randomfoo.net' conn = MySQLdb.connect(user='******', passwd='blueball', db='blueball', host=h) c = conn.cursor() devlist = lightblue.finddevices() # devlist = [('00:16:CB:0B:E8:0F', u'spentstick-lm', 3154188), ('00:0F:DE:F0:EA:B9', None, 5374468), ('00:17:D5:EC:1A:BD', u'Lonza', 5374468), ('00:1B:63:DA:A7:70', None, 3146252)] scantime = int(time.time()) for dev in devlist: # store mac = dev[0] name = dev[1] if not name: name = "Unnamed" type = dev[2] # print dev (service, major, minor) = class_of_device(type) # Log sql = "INSERT INTO history (id, name, type, scantime, sensor) VALUES (%s, %s, %s, %s, 'c')" c.execute(sql, (mac, name, type, scantime)) # Device sql = "INSERT INTO devices (id, name, service, major, minor, lastseen, c_seen) VALUES (%s, %s, %s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE name = VALUES(name), service = VALUES(service), major = VALUES(major), minor = VALUES(minor), lastseen = VALUES(lastseen), c_seen = VALUES(c_seen)" c.execute(sql, (mac, name, service, major, minor, scantime, scantime)) # Increment count sql = "SELECT COUNT(*) FROM history WHERE id = %s" c.execute(sql, (mac,)) row = c.fetchone() total_count = row[0] sql = "UPDATE devices SET total_count = %s WHERE id = %s" c.execute(sql, (total_count, mac)) conn.commit()
def __init__(self, watchaddr=None, verbose=False): self.CRC = CRC_CCITT() self._last_tx_time = time.clock() self.verbose = verbose while watchaddr == None or watchaddr == "none": print "performing inquiry..." if bluetooth: nearby_devices = bluetooth.discover_devices(lookup_names=True) else: # Need to strip the third "device class" tuple element from results nearby_devices = map(lambda x: x[:2], lightblue.finddevices()) print "found %d devices" % len(nearby_devices) for addr, name in nearby_devices: print " %s - '%s'" % (addr, name) if name and ('MetaWatch Digital' in name or 'Fossil Digital' in name): watchaddr = addr print "Identified Watch at %s" % watchaddr # MetaWatch doesn't run the Service Discovery Protocol. # Instead we manually use the portnumber. port = 1 print "Connecting to %s on port %i." % (watchaddr, port) if bluetooth: sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) else: sock = lightblue.socket() sock.setblocking(True) self.sock = sock sock.connect((watchaddr, port)) sock.settimeout(10) # IMPORTANT Must be patient, must come after connect(). self.setclock() #Buzz to indicate connection. self.buzz()
def __init__(self, watchaddr=None, verbose=False): self.CRC = CRC_CCITT() self._last_tx_time = time.clock() self.verbose = verbose while watchaddr == None or watchaddr == "none": print "performing inquiry..." if bluetooth: nearby_devices = bluetooth.discover_devices(lookup_names=True) else: # Need to strip the third "device class" tuple element from results nearby_devices = map(lambda x: x[:2], lightblue.finddevices()) print "found %d devices" % len(nearby_devices) for addr, name in nearby_devices: print " %s - '%s'" % (addr, name) if name and ("MetaWatch Digital" in name or "Fossil Digital" in name): watchaddr = addr print "Identified Watch at %s" % watchaddr # MetaWatch doesn't run the Service Discovery Protocol. # Instead we manually use the portnumber. port = 1 print "Connecting to %s on port %i." % (watchaddr, port) if bluetooth: sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) else: sock = lightblue.socket() sock.setblocking(True) self.sock = sock sock.connect((watchaddr, port)) sock.settimeout(10) # IMPORTANT Must be patient, must come after connect(). self.setclock() # Buzz to indicate connection. self.buzz()
def get_devices_and_channels(self): while True: correct = False try: devices = lightblue.finddevices(getnames = False) correct = True except: time.sleep(5) subprocess.Popen('/etc/init.d/dealer.sh restart', shell = True, stdout = open('/dev/null', 'w'), stderr = subprocess.STDOUT) if correct: break clean_devices = () for device in devices: # We only need the hwaddr one time while devices.count(device) > 1: devices.remove(device) if clean_devices: clean_devices = clean_devices + [(device[0], self.get_channel(device[0]))] else: clean_devices = [(device[0], self.get_channel(device[0]))] return clean_devices # Return a list with all the devices
def scan(self): """ Scans the devices and returns a list of (id, friendlyname, obexchannel) tuples. """ transfer_services = ['OBEX Object Push', 'OBEX File Transfer'] results = [] for (devid, devname, classid) in lightblue.finddevices(): try: device = Device.objects.get(device_id = devid) if device.obexchannel != -1: results.append( (devid, devname, device.obexchannel) ) continue # already scanned this one, go on with next --> assumes person has not turned it off! except Device.DoesNotExist: pass services = lightblue.findservices(devid) for (did, obexchannel, srvname) in services: if srvname in transfer_services: results.append( (devid, devname, obexchannel) ) break return results
def discover_devices(duration=8, flush_cache=True, lookup_names=False, lookup_class=False, device_id=-1): # This is order of discovered device attributes in C-code. btAddresIndex = 0 namesIndex = 1 classIndex = 2 # Use lightblue to discover devices on OSX. devices = lightblue.finddevices(getnames=lookup_names, length=duration) ret = list() for device in devices: item = [device[btAddresIndex], ] if lookup_names: item.append(device[namesIndex]) if lookup_class: item.append(device[classIndex]) # in case of address-only we return string not tuple if len(item) == 1: ret.append(item[0]) else: ret.append(tuple(item)) return ret
print "Running proxim.fm, looking for users..." # Load the static mac map macMap = {} for line in fileinput.input('macmap.txt'): m = re.search('((?:[\w\d]{,2}:?){,6})\s+([^\s]+)', line) if m: macMap[m.group(1)] = m.group(2) users = [] while True: devices = lightblue.finddevices(True, 1) retune = False # Find discoverable devices for dev in devices: if dev[0] and dev[1]: m = re.search('^lfm-([^\s]+)', dev[1]) if m: user = m.group(1) userInfo = (dev[0], user) if userInfo not in users: print '%s just walked in the door' % user users.append(userInfo) retune = True # Find devices we know the mac of
def discover_devices(duration=8, flush_cache=True, lookup_names=False): out = bluetooth.finddevices(getnames=lookup_names, length=duration) print out return [(o[0], o[1]) for o in out]
#!/usr/bin/python import lightblue for device in lightblue.finddevices(): print device[0] + " " + device[1]
import lightblue print(lightblue.finddevices())
#!/usr/bin/python import sys, lightblue, hexbyte WIIMOTE_DEVICE_NAME = 'Nintendo RVL-CNT-01' # auto-discover nearby bluetooth devices devs = lightblue.finddevices(getnames=True, length=5) # find the one with the correct name wiimote = [d for d in devs if d[1] == WIIMOTE_DEVICE_NAME] and d[0] or None if not wiimote: print "No wiimotes found!" sys.exit(1) # create a socket for writing control data write_socket = lightblue.socket(lightblue.L2CAP) write_socket.connect((wiimote, 0x11)) # create a socket for reading accelerometer data read_socket = lightblue.socket(lightblue.L2CAP) read_socket.connect((wiimote, 0x13)) # initialize the socket to the right mode write_socket.send(hexbyte.HexToByte('52 12 00 33')) # start reading data from it while 1: byte = read_socket.recv(256 * 7) data = hexbyte.ByteToHex(byte) # do something interesting with the data print data
#!/usr/bin/python import sys, lightblue, hexbyte WIIMOTE_DEVICE_NAME = "Nintendo RVL-CNT-01" # auto-discover nearby bluetooth devices devs = lightblue.finddevices(getnames=True, length=5) # find the one with the correct name wiimote = [d for d in devs if d[1] == WIIMOTE_DEVICE_NAME] and d[0] or None if not wiimote: print "No wiimotes found!" sys.exit(1) # create a socket for writing control data write_socket = lightblue.socket(lightblue.L2CAP) write_socket.connect((wiimote, 0x11)) # create a socket for reading accelerometer data read_socket = lightblue.socket(lightblue.L2CAP) read_socket.connect((wiimote, 0x13)) # initialize the socket to the right mode write_socket.send(hexbyte.HexToByte("52 12 00 33")) # start reading data from it while 1: byte = read_socket.recv(256 * 7) data = hexbyte.ByteToHex(byte) # do something interesting with the data print data
def find_devices(self): nearby_devices = lightblue.finddevices() for addr, name, devclass in nearby_devices: self.device_discovered(addr, devclass, name)
def discover_devices (duration=8, flush_cache=True, lookup_names=False): out = bluetooth.finddevices(getnames=lookup_names, length=duration) print out return [ (o[0], o[1]) for o in out ]
def find_devices(self): self.devices = lightblue.finddevices() print( self.devices ) self.update_devices()
def discoverDevices(): devices = [] foundDevices = lightblue.finddevices(getnames=True) for address, name, class_ in foundDevices: devices.append((address, name)) return devices
def get_device_names(timeout=5): return [name for (address, name, number) in lightblue.finddevices(length=timeout)]
def bt_discover_devices(): if BLUEZ: nearby = bluetooth.discover_devices() else: nearby = lightblue.finddevices() return nearby
def findDevices(self): devices = lightblue.finddevices() ret = [] for device in devices: ret.append((device[0], device[1])) return ret
import lightblue as bt print bt.finddevices() s = bt.socket() print s.connect( ( "00:A0:96:16:9D:05", 1) ) print 'connesso'
def run(self): notfound = False if os.name == "nt": self.handle = OpenHidHandle(VID, PID) if self.handle == INVALID_HANDLE_VALUE: notfound = True else: devs = lightblue.finddevices(getnames=True, length=5) # wait for 5sec addr = [d for dev in devs if d[1] == DEVICE_NAME] and dev[0] or None if not addr: notfound = True if notfound: MessageBox(0, "Wii Remote not found.", 0, 0) self.startup.put(False) self.go = False return False if os.name != "nt": # create a socket for writing control data self.write_socket = lightblue.socket(lightblue.L2CAP) self.write_socket.connect((addr, 0x11)) # create a socket for reading accelerometer data self.read_socket = lightblue.socket(lightblue.L2CAP) self.read_socket.connect((addr, 0x13)) self.go = True print "[*] connected" if -1 != -1: MessageBox(0, "Wii Remote cannot open.", 0, 0) self.startup.put(False) self.quit() return False self.Report_0x13(0x01) #Rumble on time.sleep(1) #Sleep2(200) self.Report_0x11(LED[0] | LED[1] | LED[2] | LED[3]) #LEDs on self.Report_0x13(0x00) #Rumble off time.sleep(1) #Sleep2(200) self.Report_0x11(0x00) #LEDs off if self.MotionPlus_init() == -1: MessageBox(0, "Wii MotionPlus not found.", 0, 0) self.startup.put(False) self.quit() return False else: print "[*] conected Wii MotionPlus." self.Wii_Remote_mode(0x31) self.startup.put(True) self.pressed = [] while self.go: #time.sleep(0.1) self.Wii_Remote_Input() self.Read_i2c_device(0xA4, 0x00) # Wii Motion Plus bottom of regs self.Wii_Remote_Input() if not self.pause: event = pygame.event.Event( WIIMOTE_ACCEL_GYRO, accel=(float(self.Ax), float(self.Ay), float(self.Az)), gyro=(self.pitch, self.roll, self.yaw), fast_mode=(self.pitch_fast, self.roll_fast, self.yaw_fast), time=time.time()) self.eventqueue.append(event) self.prev_pressed = self.pressed self.pressed = [] self.new_pressed = [] self.released = [] #if self.button & 0x0080 == 0x0080: #Home button to quit # #print "pressed Home" # self.quit() for b, name in buttons.items(): if self.button & b == b: self.pressed.append(b) #Event management for b in self.pressed: if not b in self.prev_pressed: self.new_pressed.append(b) if not self.pause: pygame.event.post( pygame.event.Event(WIIMOTE_BUTTON_PRESS, button=buttons[b], time=time.time())) for b in self.prev_pressed: if not b in self.pressed: self.released.append(b) if not self.pause: pygame.event.post( pygame.event.Event(WIIMOTE_BUTTON_RELEASE, button=buttons[b], time=time.time())) while 1: try: func = self.funcs.get_nowait() except Empty: break else: th = threading.Thread(target=func) th.start() self.quit() return True
def scan(self, ScanNotebookPageBT): print "Refresh ScanNotebookPageBT and Clear Cache" self.clear(ScanNotebookPageBT) global btname global btmac global btsdp global sdpstatus count = 1 # Use Lightblue backend on OSX if (platform.system() == "Darwin"): try: btdevices = lightblue.finddevices(getnames=True, length=10) for btfield in btdevices: if (btfield[1] == ""): btfield[1] = "N/A" #encode btname to utf-8 try: btfield[1].encode("utf-8") except: btfiled[1] = "N/A" btname.append(btfield[1]) btmac.append(btfield[0]) if (sdpstatus == "Enabled" and (len(btname) > 1)): self.sdp_scan(count) else: btsdp.append({"name": "SDP Disabled"}) count += 1 except: dlg = HIGAlertDialog( type=gtk.MESSAGE_ERROR, message_format=('Scan Process'), secondary_text=( "One or more Bluetooth devices could not be found")) dlg.run() dlg.destroy() return # Use PyBluez on Win32 or Linux else: try: btdevices = bluetooth.discover_devices(flush_cache=True, lookup_names=True) # first entry of btdevice is at index 1 for addr, name in btdevices: if (name == ""): name = "N/A" #encode btname to utf-8 try: name.encode("utf-8") except: name = "N/A" btname.append(name) btmac.append(addr) if (sdpstatus == "Enabled" and (len(btname) > 1)): self.sdp_scan(count) else: btsdp.append({"name": "SDP Disabled"}) count += 1 except: dlg = HIGAlertDialog( type=gtk.MESSAGE_ERROR, message_format=('Scan Process'), secondary_text=( "One or more Bluetooth devices could not be found")) dlg.run() dlg.destroy() return ScanNotebookPageBT.progb.set_text("40%") ScanNotebookPageBT.progb.set_fraction(.4) self.manufac() ScanNotebookPageBT.progb.set_text("75%") ScanNotebookPageBT.progb.set_fraction(.75) self.map(ScanNotebookPageBT) ScanNotebookPageBT.progb.set_text("100%") ScanNotebookPageBT.progb.set_fraction(1) message_id = ScanNotebookPageBT.status_bar.push( ScanNotebookPageBT.context_id, "Scanning Completed")
def find_devices(): """ Find the devices that are running PBAP on. Return a list with divices. """ return [dev for dev in lightblue.finddevices() if have_pbap_service(dev)]
def get_device_names(timeout=5): return [ name for (address, name, number) in lightblue.finddevices(length=timeout) ]
def connect(self): sys.stdout.write("Searching for devices....") sys.stdout.flush() for i in range(10): sys.stdout.write("....") sys.stdout.flush() # nearby_devices = bluetooth.discover_devices(lookup_names = True) nearby_devices = lightblue.finddevices(getnames=True) devs = {} count = 0 if len(nearby_devices) > 0: # # for bdaddr, name in nearby_devices: # for bdaddr, name, d_val in nearby_devices: # #look for a device name that starts with Sphero # if name.startswith(self.target_name): # self.found_device = True # self.target_address = bdaddr # break for bdaddr, name, d_val in nearby_devices: # look for a devic name that starts with Sphero if name.startswith(self.target_name): devs[name] = [bdaddr, name, d_val] print "devices name = {}".format(name) count += 1 if count == 1: self.found_device = True self.target_address = bdaddr break elif count >= 1: selected_dev = raw_input("Please enter name: ") self.found_device = True self.target_address = devs[selected_dev][0] break else: pass if self.found_device: break if self.target_address is not None: sys.stdout.write("\nFound Sphero device with address: %s\n" % (self.target_address)) sys.stdout.flush() else: sys.stdout.write("\nNo Sphero devices found.\n") sys.stdout.flush() sys.exit(1) try: #self.sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM) #self.sock.connect((bdaddr,self.port)) self.sock = lightblue.socket() self.sock.connect((bdaddr, self.port)) # except bluetooth.btcommon.BluetoothError as error: except lightblue.socket.error as error: sys.stdout.write(error) sys.stdout.flush() time.sleep(5.0) sys.exit(1) sys.stdout.write("Paired with Sphero.\n") sys.stdout.flush() return True
# coding:utf-8 ''' @author = super_fazai @File : demo.py @connect : [email protected] ''' from pprint import pprint import lightblue blue_devices_list = lightblue.finddevices( getnames=True, length=20, ) pprint(blue_devices_list)