def lookup_name(self, address, device=-1, timeout=10): """ Linux only Tries to determine the friendly name (human readable) of the device with the specified bluetooth address. Returns the name on success, and None on failure. timeout=10 how many seconds to search before giving up. """ logger.debug("Device: %s " % (device)) if sys.platform == "linux2": # NOTE: I had to rewrite this for the latest bluez, # the reason this is complicated is because I need to select the device, # before making the call. # http://code.google.com/p/pybluez/source/detail?spec=svn27&r=22 if not bluetooth.is_valid_address(address): raise ValueError("%s is not a valid Bluetooth address" % address) try: sock = _bt.hci_open_dev(device) except: raise ValueError("error accessing bluetooth device") timeoutms = int(timeout * 1000) try: name = _bt.hci_read_remote_name(sock, address, timeoutms) except _bt.error, e: # name lookup failed. either a timeout, or I/O error name = None sock.close() return name
def run(self): if not bluetooth.is_valid_address(self.deviceID): return False try: self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) #self.socket.settimeout(45) self.socket.connect((self.deviceID, 2)) except bluetooth.btcommon.BluetoothError as e: if self.die == True: return #test cancelled errorno = e.message.strip('()').split(',')[0] if errorno == '113': self.callback("Bluetooth Unavailable") elif errorno == '115': self.callback("Status: Cannot Connect") else: self.callback(e.message) return False except: print(sys.exc_info()) if self.die == True: return #test cancelled self.callback("Status: Unavailable/Unauthorised") return False if self.die == True: return #test cancelled try: self.socket.close() except: print('couldnt close socket') self.callback("Status: OK")
def establishConnectionTo(self, host): # host can also be a name, resolving it is slow though and requires the # device to be visible if not bluetooth.is_valid_address(host): nearby_devices = bluetooth.discover_devices() for bdaddr in nearby_devices: if host == bluetooth.lookup_name(bdaddr): host = bdaddr break if bluetooth.is_valid_address(host): con = BluetoothSocket(bluetooth.RFCOMM) con.connect((host, 1)) # 0 is channel self.bt_connections.append(con) return len(self.bt_connections) - 1 else: return -1
def filter(self,data): if(not data.get("loc_added", False)): data["loc_added"] = 1 data["received"] = time.time() data["timestamp"] = time.time() data['x'] = self.x data['y'] = self.y data['z'] = self.z # do we have any other metadata we could parse out of the # returrned RAW string. if(data["raw"].find("|") > -1): (addr, rssi) = data["raw"].split("|") addr = addr.strip() rssi = rssi.strip() if( not bluetooth.is_valid_address(addr)): # I should probably log this somewhere external as well. logger.error("Filtered invalid bluetooth MAC address: %s " % (addr)) return {} # filter invalid bluetooth macs data['rssi'] = int(rssi) data['addr'] = addr data['type'] = "btpacket" data['device_type'] = "bt" data['device_id'] = addr else: return {} # for now # hmm.. weird. # we could return {} to consider the packet filtered return data
def lookup_name(self,address, device=-1, timeout=10): """ Linux only Tries to determine the friendly name (human readable) of the device with the specified bluetooth address. Returns the name on success, and None on failure. timeout=10 how many seconds to search before giving up. """ logger.debug("Device: %s " % (device)) if sys.platform == "linux2": # NOTE: I had to rewrite this for the latest bluez, # the reason this is complicated is because I need to select the device, # before making the call. # http://code.google.com/p/pybluez/source/detail?spec=svn27&r=22 if not bluetooth.is_valid_address(address): raise ValueError("%s is not a valid Bluetooth address" % address) try: sock = _bt.hci_open_dev (device) except: raise ValueError("error accessing bluetooth device") timeoutms = int (timeout * 1000) try: name = _bt.hci_read_remote_name (sock, address, timeoutms) except _bt.error, e: # name lookup failed. either a timeout, or I/O error name = None sock.close() return name
def run(self): if not bluetooth.is_valid_address(self.deviceID): return False try: self.socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) #self.socket.settimeout(45) self.socket.connect((self.deviceID,2)) except bluetooth.btcommon.BluetoothError as e: if self.die == True: return #test cancelled errorno = e.message.strip('()').split(',')[0] if errorno == '113': self.callback("Bluetooth Unavailable") elif errorno == '115': self.callback("Status: Cannot Connect") else: self.callback(e.message) return False except: print(sys.exc_info()) if self.die == True: return #test cancelled self.callback("Status: Unavailable/Unauthorised") return False if self.die == True: return #test cancelled try: self.socket.close() except: print('couldnt close socket') self.callback("Status: OK")
class Bluetoothb: def lookup_name(self,address, device=-1, timeout=10): """ Linux only Tries to determine the friendly name (human readable) of the device with the specified bluetooth address. Returns the name on success, and None on failure. timeout=10 how many seconds to search before giving up. """ logger.debug("Device: %s " % (device)) if sys.platform == "linux2": bluetooth._checkaddr(address) sock = bluetooth._gethcisock(device) timeoutms = int(timeout * 1000) try: name = bluetooth._bt.hci_read_remote_name( sock, address, timeoutms ) except bluetooth._bt.error, e: print e logger.debug("Lookup Failed") # name lookup failed. either a timeout, or I/O error name = None sock.close() return name elif sys.platform == "win32": if not bluetooth.is_valid_address(address): raise ValueError("Invalid Bluetooth address") return bluetooth.bt.lookup_name( address )
def adapter_address(inter, addr=None): if addr is not None: inter = int(str(inter).replace('hci','')) if (bluetooth.is_valid_address(addr)): print('device set to ' + clone.set_adapter_address(inter,addr)) else: raise ValueError('Invalid Address: '+addr); else: s = _run(['hciconfig',inter]) return re.compile(r'Address: ([A-Fa-f0-9:]*)').findall(str(s))[0]
def adapter_address(inter, addr=None): if addr is not None: inter = int(str(inter).replace('hci', '')) if (bluetooth.is_valid_address(addr)): print('device set to ' + clone.set_adapter_address(inter, addr)) else: raise ValueError('Invalid Address: ' + addr) else: s = _run(['hciconfig', inter]) return re.compile(r'Address: ([A-Fa-f0-9:]*)').findall(str(s))[0]
def check_address_validity(self, address): """ Checks if given string address valid or not. """ if bluetooth.is_valid_address(address): print "Address '%s' is valid." % address LOG.debug("Checking address. Address %s is valid." % address) return True else: print "Address '%s' is not valid." % address LOG.warning("Checking address. Address %s is NOT valid." % address)
def __init__(self, address, num): """ Constructor """ self.num = num self.is_connected = False self.pos = calculate_light_pos(num) if bt.is_valid_address(address): self.endpoint = address else: raise ValueError("invalid Bluetooth address") return self.connect_light() self.rgb = (0,0,0)
def connect_to_brick(address, by_ip=True, by_bluetooth=True): if by_bluetooth: try: import bluetooth import bluesocket if bluetooth.is_valid_address(address): try: _MODULE_LOGGER.debug( "Bluetooth address found, trying to connect to brick") if _is_brick_already_in_memory(address, config.BLUETOOTH_PORT): return _stored_brick(address, config.BLUETOOTH_PORT) socket = bluesocket.BlueSocket() socket.connect(address, config.BLUETOOTH_PORT) _brick = brick.Brick(socket) _store_brick_in_memory(address, config.BLUETOOTH_PORT, _brick) return _brick except bluetooth.BluetoothError: raise error.BrickNotFoundException( "Did you provide the correct bluetooth address?") except ImportError: pass if by_ip: try: _MODULE_LOGGER.debug("Connecting to brick by IP") if _is_brick_already_in_memory(address, config.IP_SOCKET_PORT): return _stored_brick(address, config.IP_SOCKET_PORT) socket = ipsocket.IpSocket() socket.connect(address, config.IP_SOCKET_PORT) _brick = brick.Brick(socket) _store_brick_in_memory(address, config.IP_SOCKET_PORT, _brick) return _brick except: raise error.BrickNotFoundException( "Did you provide the correct ip address?") raise error.NoValidCommunicationChosenException( "You must choose either ip or bluetooth as a communication option")
def establishConnectionTo(self, host): # host can also be a name, resolving it is slow though and requires the # device to be visible if not bluetooth.is_valid_address(host): nearby_devices = bluetooth.discover_devices() for bdaddr in nearby_devices: if host == bluetooth.lookup_name(bdaddr): host = bdaddr break if bluetooth.is_valid_address(host): con = BluetoothSocket(bluetooth.RFCOMM) con.settimeout(0.5) # half second to make IO interruptible while True: try: con.connect((host, 1)) # 0 is channel self.bt_connections.append(con) return len(self.bt_connections) - 1 except bluetooth.btcommon.BluetoothError as e: if not self._isTimeOut(e): logger.error("unhandled Bluetooth error: %s", repr(e)) break else: return -1
def __init__(self, target_name, target_address, nb_tries): #Manage close from remote target print '=== Serial communication over bluetooth ===' print 'Initializing...' print 'Checking arguments' if target_address == None and target_name == None: print 'At least one device caracteristic needed' sys.exit(1) print ' -> ok' print 'checking address format' if not bluetooth.is_valid_address(target_address): sys.exit('Bad syntax address') print ' -> ok' self.target_name = target_name self.target_address = target_address self.nb_tries = nb_tries
def create(unique='00:02:76:FE:4E:30'): # Check we have a valid address to bind to if not bluetooth.is_valid_address(unique): return {} # Find and connect to the lego nxt #try: if True: con = {} con['id'] = unique con['sock'] = bluetooth.BluetoothSocket(bluetooth.RFCOMM) con['con'] = con['sock'].connect((unique, 1)) #except: # return {} return con
def connect_to_brick(address, by_ip=True, by_bluetooth=True): if by_bluetooth: try: import bluetooth import bluesocket if bluetooth.is_valid_address(address): try: _MODULE_LOGGER.debug("Bluetooth address found, trying to connect to brick") if _is_brick_already_in_memory(address, config.BLUETOOTH_PORT): return _stored_brick(address, config.BLUETOOTH_PORT) socket = bluesocket.BlueSocket() socket.connect(address, config.BLUETOOTH_PORT) _brick = brick.Brick(socket) _store_brick_in_memory(address, config.BLUETOOTH_PORT, _brick) return _brick except bluetooth.BluetoothError: raise error.BrickNotFoundException("Did you provide the correct bluetooth address?") except ImportError: pass if by_ip: try: _MODULE_LOGGER.debug("Connecting to brick by IP") if _is_brick_already_in_memory(address, config.IP_SOCKET_PORT): return _stored_brick(address, config.IP_SOCKET_PORT) socket = ipsocket.IpSocket() socket.connect(address, config.IP_SOCKET_PORT) _brick = brick.Brick(socket) _store_brick_in_memory(address, config.IP_SOCKET_PORT, _brick) return _brick except: raise error.BrickNotFoundException("Did you provide the correct ip address?") raise error.NoValidCommunicationChosenException("You must choose either ip or bluetooth as a communication option")
def main(): """ Sample of usage BluetoothAudio. This sample loopback audio from microphone to speaker. """ logging.basicConfig(level=logging.DEBUG, format='%(message)s') if len(sys.argv) == 1: print("Please specify device MAC address or 'scan' to scan it.") sys.exit(1) if sys.argv[1] == 'scan': nearby_devices = bluetooth.discover_devices(duration=4, lookup_names=True, flush_cache=True, lookup_class=False) print(nearby_devices) return if not bluetooth.is_valid_address(sys.argv[1]): print("Wrong device address.") return hf = BluetoothAudio(sys.argv[1], BluetoothAudio.AUDIO_16KHZ_SIGNED_16BIT_LE_MONO) # Make a test RING from headset #threading.Thread(target=demo_ring, args=[hf]).start() try: while not hf.is_connected(): time.sleep(0.1) time.sleep(1.5) hf.beep() time.sleep(0.5) hf.flush() while True: d = hf.read() if d: hf.write(d) else: time.sleep(0.5) # generate noise #hf.write(bytes(i for i in range(hf.sco_payload))) except KeyboardInterrupt: pass hf.close() logging.info('\nExiting...')
def create(unique='00:16:53:01:AD:F3'): # Check we have a valid address to bind to if not bluetooth.is_valid_address(unique): return {} # Find and connect to the lego nxt try: con = {} con['id'] = unique con['sock'] = bodies.nxt.nxt.locator.find_one_brick(host=unique) con['con'] = con['sock'].connect() # Make sure the nxt doesnt time out con['con'].keep_alive() con['con'].play_tone_and_wait(659, 250) con['con'].start_program('motors.rxe') except bodies.nxt.nxt.locator.BrickNotFoundError: return {} return con
def isValidBluetoothAddress(self, address): if USE_PYBLUEZ: return bluetooth.is_valid_address(address) elif USE_LIGHTBLUE: return lightblue._lightbluecommon._isbtaddr(address)