Exemplo n.º 1
0
    def scan(self):
        service = DiscoveryService(self.bt_interface) \
            if self.bt_interface else DiscoveryService()

        devices = service.discover(self.timeout_secs)
        return sorted([addr for addr, device in devices.items()
                       if self.service_uuid in self._get_uuids(device)])
Exemplo n.º 2
0
def search_for_authorized_eyeot_devices():
    """
    This function performs a BLE scan, finding all possible devices in range. It compares each device's name and MAC
    address against those already white listed. It returns a list of any authorized devices.

    Input: authorized_devices, a list containing the current MAC addresses of valid EyeoT devices in range

    Output: authorized_devices, a list containing the current MAC addresses of valid EyeoT devices in range
    """
    auth_devices = list()  # initialize empty
    service = DiscoveryService(
        pc.hci_num
    )  # use the USB BLE dongle at hci1, not the integrated Bluetooth card at hci0
    devices = service.discover(2)  # find all possible nearby BLE devices

    for address, name in devices.items():  # for all devices
        # if a discovered device's name and MAC address are pre-approved
        if address in arduino.mac_addresses:  # TODO: (filter also by Arduino name?)
            print("Authorized EyeoT device: {} at MAC address: {}".format(
                name, address))
            auth_devices.append(address)
        else:
            print("Rejected Device: {} at MAC address: {}".format(
                name, address))
    return auth_devices
Exemplo n.º 3
0
def list_devices_ble():
    service = DiscoveryService()
    devices = service.discover(2)

    for address, name in devices.items():
        print("searching devices BLE")
        print("name: {}, address: {}".format(name, address))
Exemplo n.º 4
0
def find_dev(dev_name):
    service = DiscoveryService()
    while True:
        devices = service.discover(2)
        for address, name in devices.items():
            if dev_name in name:
                return address
Exemplo n.º 5
0
def low_scan():
    # bluetooth low energy scan
    service = DiscoveryService()
    devices = service.discover(2)

    for address, name in devices.items():
        print("name: {}, address: {}".format(name, address))
Exemplo n.º 6
0
    def handle(self, *args, **kwargs):

        while True:

            service = DiscoveryService()
            devices = service.discover(20)

            for address in devices:
                address = str(address)
                address = address.strip()

                try:
                    b = BtScan.objects.get(bt_mac_addr=address.upper())
                    b.last_seen = datetime.now()
                    b.save()
                    print('Already known', address)

                except BtScan.DoesNotExist:
                    #  if new device, store it in this table then send off to workers to query it for services
                    b = BtScan()
                    b.created_at = datetime.now()
                    b.last_seen = datetime.now()
                    b.bt_mac_addr = address
                    b.save()
                    print('New device', address)

                    bt_device_service_discovery.delay(address)
Exemplo n.º 7
0
def find_new_xiaomi_devices(existing, duration):
    """
    Finds all new xiaomi devices by name and address.
    Assigns a new name to the device in the form:
    Sensor xx, where xx is the next available index
    """
    next_index = len(existing) + 1
    x_devices = {}
    service = DiscoveryService()
    devices = service.discover(duration)
    print(f"Scanning found {len(devices)} devices.")
    for addr, name in devices.items():
        if addr[:len(TEMP_HUM_DEV_ADDR_START)] == TEMP_HUM_DEV_ADDR_START or \
            name == TEMP_HUM_DEV_NAME:
            if addr not in existing:
                device = {
                    'dev_name': name,
                    'addr': addr,
                    'sensor_name': "Sensor %02d" % next_index,
                    'history_file':
                    f'sensor_{addr.replace(":", "")}_history.json',
                    'active': True,
                    'last_reading': None
                }
                next_index += 1
                print(f"Found new device: {name}: {addr}")
                x_devices[addr] = device
    if len(x_devices):
        print(f"Only {len(x_devices)} were new")
    else:
        print("None were new")
    return x_devices
Exemplo n.º 8
0
Arquivo: test.py Projeto: nbdy/btpy
def ble():
    s = DiscoveryService()

    devs = s.discover(2)

    for a, n in devs.items():
        print(a, n)
        g.connect(True)
Exemplo n.º 9
0
def scan_ble(duration=8):
    svc = DiscoveryService()
    devs = svc.discover(duration)
    print "Find %d devices: " % len(devs)
    if devs:
        for name, addr in devs.items():
            print name, addr
    return devs
Exemplo n.º 10
0
def bluetooth_low_energy_scan(timeout=10):
    """
    currently Linux only
    """
    if DiscoveryService is None:
        return None

    svc = DiscoveryService()
    return svc.discover(timeout)
Exemplo n.º 11
0
def addresses_with_device_name(device_name):

    service = DiscoveryService()
    devices = service.discover(2)

    addresses = [
        address for address, name in devices.items() if device_name in name
    ]

    return addresses
Exemplo n.º 12
0
def register(room_id):
    if g.user['usertype_fk'] != 1:
        response = make_response(
            "You don't have permission to register a heater", 401)
        return reponse
    db = get_db()
    if request.method == 'POST':
        error = None
        mac = request.form['mac']
        name = request.form['name']
        room_id = request.form['room_id']
        if not name:
            error = "You have to give the heater a name"
        if db.execute("SELECT * FROM heater WHERE name = ?;",
                      (name, )).fetchone() is not None:
            error = "This heater is already registered"
        if error is None:
            cur = db.execute(
                "INSERT INTO heater(mac, name, room_fk) VALUES(?, ?, ?);",
                (mac, name, room_id))
            db.commit()
            return redirect(url_for('room.view', room_id=room_id))
    rooms = db.execute("SELECT * FROM room;").fetchall()
    room = db.execute("SELECT * FROM room WHERE id = ?;",
                      (room_id, )).fetchone()
    # Scan for thermostats, try to get current status
    service = DiscoveryService()
    devices = service.discover(5)
    macs = [mac for mac in devices if devices[mac] == 'CC-RT-BLE']
    db = get_db()
    heaters = []
    for mac in macs:
        h = {}
        h['mac'] = mac
        heater = db.execute(
            "SELECT h.name, r.name as room FROM heater h JOIN room r ON h.room_fk = r.id WHERE h.mac = ?;",
            (mac, )).fetchone()
        if heater is not None:
            h['status'] = 'registered'
            h['name'] = heater['name']
            h['assigned_to'] = heater['room']
        else:
            h['status'] = 'unassigned'
        t = eq3bt.Thermostat(mac)
        try:
            t.update()
            h['target_temp'] = t.target_temperature
            h['mode'] = t.mode_readable
        except BTLEDisconnectError as e:
            print(f"Unable to connect to thermostat: {mac}")
        heaters.append(h)
    return render_template('heater/register.html',
                           rooms=rooms,
                           room=room,
                           heaters=heaters)
Exemplo n.º 13
0
def main():
    pool = Pool(processes=1)

    while True:

        svc = DiscoveryService()
        devs = svc.discover(5)

        if devs:
            for addr, _ in devs.items():
                pool.apply_async(handle_packet, [addr])
Exemplo n.º 14
0
def bluetooth_low_energy_scan(timeout=10):
    svc = DiscoveryService()
    devs = svc.discover(timeout)

    print('found', len(devs), 'Bluetooth Low Energy (Smart) devices:')

    if devs:
        for u, n in devs.items():
            print(u, n)

    return devs
 def _scan_for_bt_ble_devices(self):
     """
     :brief _scan_for_bt_ble_devices():  scan for ble devices and collect into a list.
     :description: The following function will be used to scan for bt devices within a 30m radius of
         the raspberry pi.
     """
     service = DiscoveryService()
     devices = service.discover(2)
     for addr, name in zip(devices.keys(), devices.values()):
         if self._is_verified_bt_dev(name):
             self._bt_name_dev_dict[name] = Bt_Ble_Device(addr)
Exemplo n.º 16
0
 def scan(self):
     """
     Scans for nearby BLE devices and returns their attributes
     """
     service = DiscoveryService()
     print("Scanning...")
     dev_dict = service.discover(self.scan_duration)
     devices = []
     for addr, name in dev_dict.items():
         devices.append({'name': name, 'address': addr})
     return devices
Exemplo n.º 17
0
    def __init__(self, mac="C4:C3:00:01:07:3F"):
        # Check for empty arg and correct MAC address format
        # Default MAC address is given otherwise
        if not re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()):
            print("Using default MAC: C4:C3:00:01:07:3F")
            self.mac = "C4:C3:00:01:07:3F"
        else:
            self.mac = mac

        self.service = DiscoveryService()
        self.devices = self.service.discover(2)
        self.requester = GATTRequester(self.mac, False)
    def scan_addresses_low_energy(self):
        """ Initiates a scan for bluetooth LE hardware """

        service = DiscoveryService()
        devices = []
        #print("Scanning low energy")
        for addr, name in service.discover(self.scan_timeout).items():
            devices.append(addr)
        with self.available_devices_lock:
            self.le_devices = devices
        if not self.shutdown:
            threading.Timer(self.poll_frequency, self.scan_addresses_low_energy).start()
Exemplo n.º 19
0
    def scan(self):
        if self.bt_interface:
            service = DiscoveryService(self.bt_interface)
        else:
            service = DiscoveryService()

        print('Scanning for bluetooth low-energy devices')
        devices = list(service.discover(self.scan_timeout).keys())
        print('Discovering Switchbot services')
        return [
            dev for dev in devices
            if self.is_switchbot(dev, self.bt_interface, self.connect_timeout)
        ]
Exemplo n.º 20
0
def discover_camera():
    cameras = []
    service = DiscoveryService()
    devices = service.discover(2)
    for address, name in devices.items():
        if name.startswith("GoPro"):
            cameras.append([name, address])
    if len(cameras) == 0:
        print("No cameras detected.")
        exit()
    if len(cameras) == 1:
        return cameras[0][1]
    for index, i in enumerate(cameras):
        print("[{}] {} - {}".format(index, i[0], i[1]))
    return cameras[int(input("ENTER BT GoPro ADDR: "))][1]
Exemplo n.º 21
0
    def discover_btle(self):
        if DiscoveryService is None:
            return

        logging.info("Scanning lowenergy devices")
        ledevices = DiscoveryService().discover(10)
        timestamp = datetime.now().isoformat()
        logging.info("Discovered %d low energy devices" %
                     len(ledevices.keys()))
        for address, name in ledevices.items():
            if name is not None and len(name) == 0:
                name = None
            if name is not None:
                self.send_reading('/'.join([address, "name"]), name)
            self.send_reading('/'.join([address, "le"]), True)
            self.send_reading('/'.join([address, "last_seen"]), timestamp)
Exemplo n.º 22
0
    def scan(self, interface: Optional[str] = None, duration: int = 10) -> BluetoothScanResponse:
        """
        Scan for nearby bluetooth low-energy devices

        :param interface: Bluetooth adapter name to use (default configured if None)
        :param duration: Scan duration in seconds
        """
        from bluetooth.ble import DiscoveryService

        if interface is None:
            interface = self.interface

        self._check_ble_support()
        svc = DiscoveryService(interface)
        devices = svc.discover(duration)
        return BluetoothScanResponse(devices)
Exemplo n.º 23
0
def fixtureServer():
    import requests
    import socket
    global lat
    global lon
    global location
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']

    location = socket.gethostname()
    print "Location is " + location
    print "Latitude is " + str(lat)
    print "Longitude is " + str(lon)

    service = DiscoveryService()

    client = mqtt.Client("sensortagList")
    mqtt.Client.connected_flag = False
    client.on_connect = onConnect
    client.connect("127.0.0.1")
    client.on_message = onMessage
    client.loop_start()
    # Wait for connection
    while not client.connected_flag:
        pass
    # Subscribe to topics that control the tags behaviour
    client.subscribe("selectTag")
    #.subscribe("controlTag")

    # While we are connected
    while client.connected_flag:
        devices = service.discover(2)
        # scan for devices
        scan(devices)
        # stream MQTT data
        print fixture_list
        client.publish("fixture_list",
                       payload=json.dumps(fixture_list),
                       qos=2,
                       retain=False)
        time.sleep(1)

    client.loop_stop()
    client.disconnect()
Exemplo n.º 24
0
 def __init__(self, devName, bleAccessToken):
     self.onScan = async .SubscribeHub()
     self.devName = devName
     self._token = bleAccessToken
     self._thread = _ScanThread_(DiscoveryService(devName), self._token,
                                 self._onDeviceDiscovered)
     self._seenMbs = collections.OrderedDict()
     self._notMbs = collections.deque(maxlen=self.max_seen_mbs)
Exemplo n.º 25
0
class BLEScanner(DeviceScanner):

    def __init__(self, observation_queue):
        DeviceScanner.__init__(self, observation_queue)
        self.service = DiscoveryService()

    def scan(self):
        return self.service.discover(self.timeout)
Exemplo n.º 26
0
    def scanBLE(ser):
        postList = []
        service = DiscoveryService()
        devices = service.discover(2)

        l = []

        for address, name in devices.items():
            address = address.replace(':', '')
            address = [
                address[i * 2:i * 2 + 2] for i in xrange(len(address) / 2)
            ]
            #print (address)
            l.extend(address)

        #print (l)
        return l
Exemplo n.º 27
0
 def find_devices(self):
     mac_addrs = []
     nearby_devices = bluetooth.discover_devices()
     if nearby_devices:
         be_addrs = [addr for addr, name in nearby_devices]
         if be_addrs:
             mac_addrs.extend(be_addrs)
     service = DiscoveryService()
     devices = service.discover(2)
     be_le_addrs = devices.keys()
     if be_le_addrs:
         mac_addrs.extend(be_le_addrs)
     if mac_addrs:
         mac_addrs = [
             self.get_mac_vendor(mac_addr) for mac_addr in mac_addrs
             if self.get_mac_vendor(mac_addr)
         ]
     return mac_addrs
Exemplo n.º 28
0
def scanForBTDevices():
    bt_devices = {"devices_classic": {0: {}}, "devices_ble": {0: {}}}

    devices = bluetooth.discover_devices(lookup_names=True)
    i = 0
    for dev in devices:
        x, y = dev
        bt_devices["devices_classic"][i] = {"name": y, "addr": x}
        i += 1

    service = DiscoveryService()
    devices = service.discover(2)
    i = 0
    for key in devices.keys():
        bt_devices["devices_ble"][i] = {"name": devices[key], "addr": key}
        i += 1

    #(lambda x: print(devices[x]))(devices.keys)
    #print(bt_devices)
    json_devices = json.dumps(bt_devices, indent=4)
    print(json_devices)
Exemplo n.º 29
0
def main():
    connected = 0
    error = None
    target_addr = " "

    if request.method == 'POST':
        target_addr = request.form['ConnName']

        service = DiscoveryService()
        devices = service.discover(2)

        for bluetooth_addr, name in devices.items():
            if target_addr == bluetooth_addr:
                connected = 1
                return redirect(url_for('connect'))

        # for bluetooth_addr in nearby_devices:
        # 	if target_name == bluetooth.lookup_name(bluetooth_addr):
        # 		target_address = bluetooth_addr
        # 		connected = 1
        # 		return redirect(url_for('connect'))

    return render_template("bluetooth.html", connection=connected)
Exemplo n.º 30
0
#!/usr/bin/env python3

from bluetooth.ble import DiscoveryService

service = DiscoveryService()
devices = service.discover(2)

for address, name in devices.items():
    print("name: {}, address: {}".format(name, address))
Exemplo n.º 31
0
    def scan(self):
        service = DiscoveryService(self.bt_interface) \
            if self.bt_interface else DiscoveryService()

        devices = service.discover(self.timeout_secs)
        return list(devices.keys())
Exemplo n.º 32
0
# bluetooth low energy scan
from bluetooth.ble import DiscoveryService

service = DiscoveryService()
devices = service.discover(2)

for address, name in devices.items():
    print("name: {}, address: {}".format(name, address))