Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
 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
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
    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
Ejemplo n.º 5
0
 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
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
 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
Ejemplo n.º 8
0
Archivo: BLE.py Proyecto: gsauls/BLE
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
Ejemplo n.º 9
0
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
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
    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
Ejemplo n.º 13
0
    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
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
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]
Ejemplo n.º 17
0
    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
Ejemplo n.º 18
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
Ejemplo n.º 19
0
    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))
Ejemplo n.º 20
0
from __future__ import division
from gattlib import DiscoveryService
from gattlib import GATTRequester, GATTResponse
import time
import os

service = DiscoveryService("hci1")
devices = service.discover(2)
tag_address = "B0:B4:48:BF:C3:83"

for address, name in devices.items():
    print("name: {}, address: {}".format(name, address))
    if address == tag_address:
        print "cilia found"
        req = GATTRequester(tag_address, False, "hci1")
        response = GATTResponse()
        req.connect()
        req.read_by_handle_async(0x3A, response)
        while not response.received():
            time.sleep(0.1)

        steps = response.received()[0]
        #print "steps..."
        #print type(steps)
        #print steps
        #for b in steps:
        #	print hex(ord(b)),' '

        req.write_by_handle(0x3C, str(bytearray([0xff, 0xff])))
        req.write_by_handle(0x3E, str(bytearray([0x64])))
        data = req.read_by_handle(0x3C)[0]
Ejemplo n.º 21
0
#!/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")
#!/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
Ejemplo n.º 23
0
def scan():
    service = DiscoveryService("hci0")
    devices = service.discover(2)
    return devices
Ejemplo n.º 24
0
 def GetDeviceList(self):
     service = DiscoveryService("hci0")
     device = service.discover(2)
     return device
Ejemplo n.º 25
0
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)
Ejemplo n.º 26
0
def findBT4LEDevices(device="hci0", timeout=3):
    service = DiscoveryService(device)
    devices = service.discover(timeout)  # timeout in sec
    return devices.items()
Ejemplo n.º 27
0
                    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)))
Ejemplo n.º 28
0
 def up(self, json):
     service = DiscoveryService("hci0")
     device = service.discover(2)
     return device
Ejemplo n.º 29
0
#!/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))
Ejemplo n.º 30
0
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)