def scan_devices(self): if platform == 'win' or platform == 'linux' or platform == 'macosx': root = True devices = {'classic': [], 'ble': []} # bt classic try: devices['classic'] = bluetooth.discover_devices( duration=4, lookup_names=True, flush_cache=True, lookup_class=False) except OSError as error: if error.args[0] == 19: raise BluetoothExtendedError(1, 'Bluetooth not enabled') else: raise BluetoothExtendedError( 10, 'Unknown error: ' + error.args[1]) return # bt ble if platform == 'linux': service = DiscoveryService("hci0") try: devices_ble = service.discover(2) except RuntimeError as error: root = False else: for key in devices_ble: devices['ble'].append((key, devices_ble[key])) return devices, root
def discover_devices(nearby_devices=[]): timeout = BT_SCAN_TIMEOUT print("looking for nearby devices...") try: nearby_devices += bluetooth.discover_devices(lookup_names=True, flush_cache=True, duration=timeout) print("found %d devices" % len(nearby_devices)) if BT_BLE: service = DiscoveryService() try: devices = service.discover(timeout) for addr, name in devices.items(): if not name or name is "": b = BleClient(addr) name = b.request_data().decode('utf-8') b.disconnect() nearby_devices += ((addr, name)) except RuntimeError as err: print("~ BLE ~ Error ", err) else: print("found %d devices (ble)" % len(devices.items())) return nearby_devices except bluetooth.btcommon.BluetoothError as err: print(" Main thread error : %s" % (err)) exit(1)
def _get_pavlok_mac_addr(self, device): 'Find Pavlok, return its MAC address' service = DiscoveryService(device) devices = service.discover(3) #3 seconds timeout for addr, name in devices.items(): if name.startswith('Pavlok'): self.logger.debug('Found Pavlok with MAC address %s', addr) return addr
def scanner(): service = DiscoveryService() devices = service.discover(2) results = dict() for addr, name in devices.items(): if addr.startswith("00:07:80"): results[addr] = name return results
def discover_ble_devices(): """Discover Bluetooth LE devices.""" _LOGGER.debug("Discovering Bluetooth LE devices") service = DiscoveryService() devices = service.discover(10) _LOGGER.debug("Bluetooth LE devices discovered = %s", devices) return devices
def scanner ( ): service = DiscoveryService( ) devices = service.discover(2) results = dict( ) for addr, name in devices.items( ): if addr.startswith("00:07:80"): results[addr] = name return results
def findDeviceAddrByName(name_to_find, device="hci0", timeout=3): service = DiscoveryService(device) devices = service.discover(timeout) # timeout in sec device_list = devices.items() address_found = "" if len(device_list) > 0: for address, name in list(device_list): if name == name_to_find: address_found = address return address_found
def findDeviceAddrByName(name_to_find, device="hci0", timeout=3): service = DiscoveryService(device) devices = service.discover(timeout) # timeout in sec device_list = devices.items() address_found = "" if len(device_list)>0: for address, name in list(device_list): if name == name_to_find: address_found = address return address_found
def scan( str, str1 ): print("Scanning for {}...\n".format(str1)) service = DiscoveryService() devices = service.discover(8) for address, name in devices.items(): if address == str: print("Beacon found - device: {}\n".format(str1)) return True return False
def discover_ble_devices(): """Discover Bluetooth LE devices.""" _LOGGER.debug("Discovering Bluetooth LE devices") try: service = DiscoveryService() devices = service.discover(duration) _LOGGER.debug("Bluetooth LE devices discovered = %s", devices) except RuntimeError as error: _LOGGER.error("Error during Bluetooth LE scan: %s", error) devices = [] return devices
def discover_ble_devices(): """Discover Bluetooth LE devices.""" _LOGGER.debug("Discovering Bluetooth LE devices") try: service = DiscoveryService(ble_dev_id) devices = service.discover(duration) _LOGGER.debug("Bluetooth LE devices discovered = %s", devices) except RuntimeError as error: _LOGGER.error("Error during Bluetooth LE scan: %s", error) devices = [] return devices
def SensorTagDeviceScan(bt_adapter, scan_ttl): """ Discovers BTLE devices that describe themselves as a SensorTag. """ service = DiscoveryService(bt_adapter) devices = service.discover(scan_ttl) for key in devices.keys(): if 'SensorTag' not in devices[key]: del devices[key] return devices
def discover(): # Make sure the Bluetooth dongle is running p1 = subprocess.Popen(["hciconfig"], stdout=sys.stdout) p1.communicate() dongle = raw_input("Enter the appropriate hci (E.g., hci1): ") p2 = subprocess.Popen(["hciconfig", dongle, "up"], stdout=sys.stdout) p2.communicate() # Scan time scan_time = int( raw_input("Number of seconds to scan for devices (Numbers only): ")) # X seconds from now timeout = time() + scan_time # List of discovered devices device_list = [] # Scan for <timeout> seconds while True: if time() > timeout: break service = DiscoveryService(dongle) devices = service.discover(2) for address, name in devices.items(): print("Name: {} | Address: {}".format(name, address)) vendor = get_vendor(address) device_list.append("Name: {} | Address: {} | Vendor: {}".format( name, address, vendor)) # List of unique devices unique_array = np.unique(device_list) # Save discoveries to a timestamped file, including: Name, BTADDR, Vendor now = datetime.now() current_year = str(now.year) current_month = str(now.month) current_day = str(now.day) latest_scan = current_year + current_month + current_day + "_scan.txt" try: with open(latest_scan, 'a+') as f: for item in unique_array: f.write("{}\n\n".format(item)) except Exception as e: print(e)
def devices(): from gattlib import DiscoveryService service = DiscoveryService("hci0") devices = service.discover(2) res = {} for address, name in devices.items(): print("name: {}, address: {}".format(name, address)) if name.startswith('edison'): res[name] = address return jsonify(res)
def connect(self, bt_iface_name='hci0', hub_mac=None): service = DiscoveryService(bt_iface_name) while not self.requester: log.info("Discovering devices using %s...", bt_iface_name) devices = service.discover(1) log.debug("Devices: %s", devices) for address, name in devices.items(): if name == LEGO_MOVE_HUB or hub_mac == address: logging.info("Found %s at %s", name, address) self.requester = Requester(address, True, bt_iface_name) break return self
def cmd_list_devices(self, *args): print("Listing Bluetooth LE devices in range. Press CTRL+C to stop searching.") service = DiscoveryService() print("{: <12} {: <12}".format("Name", "Mac address")) print("{: <12} {: <12}".format("----", "-----------")) try: while 42: for device_mac, device_name in service.discover(2).items(): print("{: <12} {: <12}".format(device_name, device_mac)) print("---------------") time.sleep(1) except KeyboardInterrupt: print("\n")
def __init__(self): service = DiscoveryService("hci0") devices = service.discover(2) for address, name in devices.items(): if name != '' and 'nemo-wedo2' in name: print(name) req = GATTRequester(address, True, "hci0") break if 'req' not in dir(): print('Connecting to wedo2.0 hub is failed!') os._exit(0) self.req = req
def connect(self, hub_mac=None, hub_name=None): service = DiscoveryService(self._iface) while not self.requester: log.info("Discovering devices using %s...", self._iface) devices = service.discover(1) log.debug("Devices: %s", devices) for address, name in devices.items(): if self._is_device_matched(address, name, hub_mac, hub_name): self.requester = Requester(address, True, self._iface) break if self.requester: break return self
def smart_hub_connect(): service = DiscoveryService("hci0") devices = service.discover(2) for address, name in devices.items(): if name != '' and 'Smart Hub' in name: label['text'] = address global button_run, button_stop, button_disconnect, req button_connect['state'] = 'disabled' button_run['state'] = 'normal' button_stop['state'] = 'normal' button_disconnect['state'] = 'normal' button_up['state'] = 'normal' button_down['state'] = 'normal' req = GATTRequester(address, True, "hci0") break
def find(): from gattlib import DiscoveryService service = DiscoveryService("hci0") devices = service.discover(2) adrs = [] for address, name in devices.items(): if name == KONASHI_VERSION: print "found " + KONASHI_VERSION + ", " + address adrs.append(address) if adrs == []: print KONASHI_VERSION + " device not found" exit() return adrs[0]
def findCameras(self, doprint=False): """Find cameras via low energy blootooth. This method requires gattlib and root privileg. """ from gattlib import DiscoveryService try: service = DiscoveryService("hci0") devices = service.discover(2) except RuntimeError: print('Discovering devices failed. Are you root and do you have a bluetooth device?') return None if self.verbose or doprint: print("Found cameras:") for address, name in devices.items(): print("name: {}, address: {}".format(name, address)) return devices # TODO: This returns all bluetooth LE devices
def connect(self, hub_mac=None): service = DiscoveryService(self._iface) while not self.requester: log.info("Discovering devices using %s...", self._iface) devices = service.discover(1) log.debug("Devices: %s", devices) for address, name in devices.items(): if address != "00:00:00:00:00:00": if (not hub_mac and name == LEGO_MOVE_HUB) or hub_mac == address: logging.info("Found %s at %s", name, address) self.requester = Requester(address, True, self._iface) break if self.requester: break return self
def bleScanMain(timeout, adapter): """ Scan for BTLE Devices and print out results :param timeout: Scan timeout (seconds) :param adapter: Host adapter to use for scanning (Use empty string to use host's default adapter) :type timeout: int :type adapter: str :return: Tuple (deviceName, deviceAddress) :rtype: tuple (str, str) """ if timeout < 0: raise Exception( "%s is an invalid scan timeout value. The timeout must be a positive integer" % timeout) if adapter != "": service = DiscoveryService(adapter) else: service = DiscoveryService() devices = service.discover(timeout) return devices
def cmd_list_devices(self, *args): try: service = DiscoveryService(self.bluetooth_adapter) except RuntimeError as e: logger.error('Problem with the Bluetooth adapter : {}'.format(e)) return False print('Listing Bluetooth LE devices in range. Press CTRL+C to stop searching.') print('{: <12} {: <12}'.format('Name', 'Mac address')) print('{: <12} {: <12}'.format('----', '-----------')) try: while 42: for device_mac, device_name in service.discover(2).items(): print('{: <12} {: <12}'.format(device_name, device_mac)) print('---------------') time.sleep(1) except KeyboardInterrupt: print('\n') except RuntimeError as e: logger.error('Error while trying to list bluetooth devices : {}'.format(e))
def findCameras(self, doprint=False): """Find cameras via low energy blootooth. This method requires gattlib and root privileg. """ from gattlib import DiscoveryService try: service = DiscoveryService("hci0") devices = service.discover(2) except RuntimeError: print( 'Discovering devices failed. Are you root and do you have a bluetooth device?' ) return None if self.verbose or doprint: print("Found cameras:") for address, name in devices.items(): print("name: {}, address: {}".format(name, address)) return devices # TODO: This returns all bluetooth LE devices
def connect(self): while 1: #Until device was found print("Scanning for SmartWatches") service = DiscoveryService("hci0") count = 0 addresses = {} names = {} while (count==0): devices = service.discover(2) for address, name in devices.items(): count+=1 addresses[count] = address names[count] = name print(" [{}] {} - {}".format(count, name, address)) print ("Scan finished") if (count==1 and names[1].find("SmartWatch")==0): print ("Autoconnect to {}".format(names[1])) self.address = addresses[1] break address = int(input("\nEnter address index: ")) if (address>count or address<1): print("Error: Selected address does not exist\n") else: self.address = addresses[address] break print("Connecting...") self.requester = Requester(self.received, self, self.address) n = 0 while self.requester.is_connected()!=1: sleep(0.5) n+=1 if (n>6): print("Connection failed") return False return self.status()
def cmd_list_devices(self, *args): try: service = DiscoveryService(self.bluetooth_adapter) except RuntimeError as e: logger.error('Problem with the Bluetooth adapter : {}'.format(e)) return False print( 'Listing Bluetooth LE devices in range. Press CTRL+C to stop searching.' ) print('{: <12} {: <12}'.format('Name', 'Mac address')) print('{: <12} {: <12}'.format('----', '-----------')) try: while 42: for device_mac, device_name in service.discover(2).items(): print('{: <12} {: <12}'.format(device_name, device_mac)) print('---------------') time.sleep(1) except KeyboardInterrupt: print('\n') except RuntimeError as e: logger.error( 'Error while trying to list bluetooth devices : {}'.format(e))
def lescan(): #define global variables global time global scanTime global scanCount global scatter_devs global scatter_colour global scatter_time global devicesDictionary global totaldevCount global newdevCount global knowndevCount global time_list # set the service to a discoveryservice from the bluetooth adapter, HCI0 for internal adapter, HCI1 for external service = DiscoveryService("hci0") #carry out a LE scan for the time specified ScanDevices = service.discover(scanTime) #set variables to 0 to clear from previous scan count = 0 knownCount = 0 unknownCount = 0 #increase time by the scan time, in order to increase the time_passed time = time + scanTime time_passed.append(time) ######################################################################### ## plot relevant data to graph data sets - s.write("\n -------------------------------------------") s.write("\n\n Scan Time : " + str(time)) #for each device found in the scan, add 1 to the amount of devices found, and add these to the graph lists for address, name in ScanDevices.items(): count = count + 1 addresses.append(format(address)) scatter_time.append(time) #if the device is in blacklist, then alert the user for key in blackListDict: if key == str(address): tkMessageBox.showinfo(title="Device In Range!", message="Device found, \n\n" + str(blackListDict[str(address)]) + "\n\n " + str(address)) #if the address is in devices dictionary, gat its ID and plot it if str(address) in devicesDictionary: id = devicesDictionary.get(str(address)) scatter_devs.append(id) knownCount = knownCount + 1 s.write("\n " + str(id) + " : " + str(address)) # if the device is new, else: id = (len(devicesDictionary) + 1) devicesDictionary.update({str(address): id}) colour = "#{:06x}".format(random.randint(0, 0xFFFFFF)) colourDictionary.update({id: colour}) scatter_devs.append(id) unknownCount = unknownCount + 1 s.write("\n " + str(id) + " : " + str(address)) totalDevs = unknownCount + knownCount totaldevCount.append(totalDevs) newdevCount.append(unknownCount) knowndevCount.append(knownCount) devices_count.append(count) return (time_passed, devices_count, scatter_time, scatter_devs, scatter_colour, totaldevCount, newdevCount, knowndevCount)
from gattlib import GATTRequester from gattlib import DiscoveryService import requests host = { "ip": "128.2.20.131", "port": 50000, "endpoint": "values" } def post(host, data): r = requests.post("http://{}:{}/{}".format(host["ip"], host["port"], host["endpoint"]), data=data) print r.status_code, r.reason, r.text return r.text service = DiscoveryService() devices = service.discover(2) for addr, name in devices.items(): print("%s (%s)" % (name,addr)) print(name) if(name=="RapidPrototype"): req=GATTRequester(addr,False) req.connect(True) status="connected" if req.is_connected() else "not connectd" print(status) prevData="00" while(True): data=req.read_by_uuid("A495FF21-C5B1-4B44-B512-1370F02D74DE") data=str(data) data=data[4:6]
def main(): description = "Wavelet Device Communication Module" parser = argparse.ArgumentParser(description=description) parser.add_argument('--blink', dest='blink', help="Blink the red LED of the device", action='store_true') parser.add_argument('--device', dest='dev_macs', help="MAC address of the device", nargs='+') parser.add_argument('--download', dest='download', help="Download device log", action='store_true') parser.add_argument('--file', dest='fname', help="Path and the basename of the file to save the raw data to") parser.add_argument('--list', dest='discover', help="List all devices.", action='store_true') parser.add_argument('--log', dest='log_dir', help="Directory to save log files to") parser.add_argument('--raw', dest='raw', help="Download log files instead of compressed ones", action='store_true') parser.add_argument('--start', dest='config', help="Start downloading all devices using a yaml config file") parser.add_argument('--status', dest='status', help="Print the status of the devices", action='store_true') parser.add_argument('--stdout', dest='stdout', help="Print to screen", action='store_true') if len(sys.argv) == 1: parser.print_help() options = parser.parse_args() if options.discover: from gattlib import DiscoveryService service = DiscoveryService() print("Discovering devices nearby...") sys.stdout.flush() devices = service.discover(2) if not len(devices): print("Looking more ...") devices = service.discover(5) if not len(devices): print("No device found") return print("{:<20} {:<20} ".format('MAX Address', 'Name')) for k, v in devices.items(): print("{:<20} {:<20} ".format(k, v)) elif options.config: start_pool(options.config) elif options.dev_macs: # Check all the mac addresses to be valid for dev_mac in options.dev_macs: if not is_mac_valid(dev_mac): raise ValueError("{} is not a valid MAC address!".format(dev_mac)) if options.blink: command = Commands.BLINK elif options.download: command = Commands.DOWNLOAD elif options.status: command = Commands.STATUS else: parser.print_help() return if not options.fname: options.fname = "./data/WED_data" if not options.log_dir: options.log_dir = "./logs/" process_list = [] for idx, dev in enumerate(options.dev_macs): stop_event = Event() wake_up = Event() if command == Commands.DOWNLOAD and not options.stdout: log_file = os.path.join(options.log_dir, "log_%s.log" % dev.replace(':', '')) else: log_file = None kwargs = {'mac_address': dev, 'command': command, 'backend_lock': backend_lock, 'log_file': log_file, 'fname': options.fname, 'wake_up': wake_up, 'stop_event': stop_event, } p = Process(target=start_command, kwargs=kwargs) process_list.append((p, wake_up, stop_event)) for p in process_list: p[0].start() try: for p in process_list: p[0].join() except (KeyboardInterrupt, SystemExit): delay = 4 * len(options.dev_macs) print("\nCancelling downloads / Waiting %d seconds for all devices to clean up....\n" % delay) time.sleep(delay) for p in process_list: p[0].terminate() sys.exit(0) except: raise
def GetDeviceList(self): service = DiscoveryService("hci0") device = service.discover(2) return device
import logging import sys import sqlite3 conn = sqlite3.connect('offline.db') c = conn.cursor() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') url = "http://127.0.0.1:5000" discoverDevice = "hci0" controller = "controller001" requestUrl = "%s/uri/cronologia" % url #invoke the "DiscoveryService" class service = DiscoveryService(discoverDevice) #declaration of the two dictionaries "controlledDevices" and "states" controlledDevices = dict() states = dict () by = dict() hello = [] offlineDevicesList = [] offlineDevicesIn = [] offlineDevicesOut = [] offlineDevices = dict() compare = dict() devices = service.discover(4) compare = devices
import sys from gattlib import DiscoveryService service = DiscoveryService("hci0") possibleTargets = list() ### # Scan for advertising packets and get AdvAs ### def doDiscovery(): global possibleTargets # check 5 times for advertising devices for x in range(0,10): # use gattlib to scan for possible target advertisers devices = service.discover(2) # loop through scan results for dev in devices.items(): # check to see if the detected device is not already in our list if dev not in possibleTargets: # not in the list, add it! possibleTargets.append(dev) # my dev is an immutable list *menna frenna* if len(dev[1].strip()) == 0: name ="No name provided." else: name = dev[1] # add device to the device selection menu
#!/usr/bin/python import time import sqlite3 #from gattlib import BeaconService from gattlib import DiscoveryService service = DiscoveryService() devices = service.discover(3) #3 segundos while True: for address, name in devices.items(): #print("nombre: {}, direccion: {}".format(name, address)) varDateTime = time.strftime("%c") varHour = time.strftime("%H:%M:%S") varDay = time.strftime("%d") varMonth = time.strftime("%B") varYear = time.strftime("%Y") varBeaconMAC = address #print(devices.items()) #varBeaconMAC = address, name in devices.items() print("Fecha y hora de la deteccion: " + varDateTime) print("Hora de la deteccion: " + varHour) print("Dia de la deteccion: " + varDay) print("Mes de la deteccion: " + varMonth) print("Anio de la deteccion: " + varYear) print("Direccion MAC del Beacon detectado: " + varBeaconMAC) #os.system("python connectDB.py")
help='hci device name (e.g. hci0)', default='hci0', dest='device') parser.add_argument('-l', '--listen', help='listen to advertises', action='store_true', dest='is_info') args = parser.parse_args() if args.btaddr is None and args.is_info is False: print 'You should specify at least one argument.' parser.print_help() exit(1) elif args.is_info: ble_discovery = DiscoveryService(args.device) devices = ble_discovery.discover(2) for device_address, device_name in devices.items(): print("name: {}, address: {}".format(device_name, device_address)) else: gatt_requester = GATTRequester(args.btaddr) print "Device Name: %s" % read_data(gatt_requester, NAME_UUID) print "Device Serial Number: %s" % read_data(gatt_requester, SERIAL_NUMBER_UUID) print "Device Software Revision: %s" % read_data(gatt_requester, SOFTWARE_REVISION_UUID) print "Device System ID: %s" % hexlify( read_data(gatt_requester, SYSTEM_ID_UUID)) print "Device PNP ID: %s" % hexlify(read_data(gatt_requester, PNP_ID_UUID)) print "Device Current Timestamp: %s" % parse_timestamp( hexlify(read_data(gatt_requester, CURRENT_TIMESTAMP_UUID)))
#!/usr/bin/python import paho.mqtt.publish as publish from gattlib import DiscoveryService import time import rfidiot serviceBLE = DiscoveryService() #topic = "hotel/raspberry1/restaurantes" topic = "ihotel/CiDa5TyIKDsYWbCCheF9/restaurantes" broker = "broker.hivemq.com" def scanBLE(): devices = serviceBLE.discover(2) for address, name in devices.items(): print("name:{}, address:{}".format(name, address)) return (address) def mqtt_pub(message): try: publish.single(topic, str(message), hostname=broker) except: print("[ERROR]") def scanNFC(): print("Inicio Deteccion TAG NFC") try: card = rfidiot.card
#!/usr/bin/env python3 from gattlib import DiscoveryService #from bluetooth import * #service = DiscoveryService("hci0") def callback(self, address, name, rssi, *args): # advertising data can contain more than just address and name, so passing the whole data array in args could be cool print("saw a device! ", address) DiscoveryService.discover(callback) # #subclassing DeviceDiscoverer and overriding a couple methods # class Discovery(DeviceDiscoverer): # def __init__(self): # DeviceDiscoverer.__init__(self) # def device_discovered(self, address, device_class, name): # print("Discovered a Device: ", address) # d = Discovery() # d.find_devices(lookup_names=False) #devices = service.discover(2) #for address, name in devices.items():
from gattlib import GATTRequester, DiscoveryService service = DiscoveryService() devices = service.discover(2) address = None for addr, name in devices.items(): if "CA" in addr: address = addr print(address) req = GATTRequester(address) try: name = req.read_by_uuid('8888')[0] print("uuid name ", name) except: print("not uuid") try: name = req.read_by_handle('8888')[0] print("handle name ", name) except: print("not handle") print(req) print(name)
def scan(): service = DiscoveryService("hci0") devices = service.discover(2) return devices
from gattlib import DiscoveryService, BeaconService service = DiscoveryService("Automatic Lights") devices = service.discover(1) for addr, name in devices.items(): print("name: {}, addr : {}".format(name, addr)) print(devices) service = BeaconService() x = service.scan(15) print(x)
#!/usr/bin/env python3 # cat /usr/local/lib/python3.7/dist-packages/gattlib-0.20200929.dist-info/METADATA from gattlib import DiscoveryService service = DiscoveryService("hci0") devices = service.discover(2) for address, name in devices.items(): print("name: {}, address: {}".format(name, address))
def findBT4LEDevices(device="hci0", timeout=3): service = DiscoveryService(device) devices = service.discover(timeout) # timeout in sec return devices.items()