Beispiel #1
0
    def connect(self):
        scanner = Scanner().withDelegate(DefaultDelegate())
        deviceFound = False
        searchCount = 0
        while deviceFound is False and searchCount < 50:
            devices = scanner.scan(0.1)  # 0.1 seconds scan period
            searchCount += 1
            for dev in devices:
                ManuData = dev.getValueText(255)
                SN = parseSerialNumber(ManuData)
                if (SN == int(self.SN)):
                    MacAddr = dev.addr
                    deviceFound = True  # exits the while loop on next conditional check
                    break  # exit for loop

        if (deviceFound is not True):
            print "ERROR: Could not find device."
            print "GUIDE: (1) Please verify the serial number. (2) Ensure that the device is advertising. (3) Retry connection."
            sys.exit(1)
        else:
            self.periph = Peripheral(MacAddr)
            self.datetime_char = self.periph.getCharacteristics(
                uuid=self.UUID_DATETIME)[0]
            self.humidity_char = self.periph.getCharacteristics(
                uuid=self.UUID_HUMIDITY)[0]
            self.temperature_char = self.periph.getCharacteristics(
                uuid=self.UUID_TEMPERATURE)[0]
            self.radon_st_avg_char = self.periph.getCharacteristics(
                uuid=self.UUID_RADON_ST_AVG)[0]
            self.radon_lt_avg_char = self.periph.getCharacteristics(
                uuid=self.UUID_RADON_LT_AVG)[0]
 def connect(self):
     # Auto-discover device on first connection
     if (self.MacAddr is None):
         scanner     = Scanner().withDelegate(DefaultDelegate())
         searchCount = 0
         while self.MacAddr is None and searchCount < 50:
             devices      = scanner.scan(0.1) # 0.1 seconds scan period
             searchCount += 1
             for dev in devices:
                 ManuData = dev.getValueText(255)
                 SN = parseSerialNumber(ManuData)
                 if (SN == self.SN):
                     self.MacAddr = dev.addr # exits the while loop on next conditional check
                     break # exit for loop
         
         if (self.MacAddr is None):
             print "ERROR: Could not find device."
             print "GUIDE: (1) Please verify the serial number."
             print "       (2) Ensure that the device is advertising."
             print "       (3) Retry connection."
             sys.exit(1)
     
     # Connect to device
     if (self.periph is None):
         self.periph = Peripheral(self.MacAddr)
     if (self.curr_val_char is None):
         self.curr_val_char = self.periph.getCharacteristics(uuid=self.uuid)[0]
Beispiel #3
0
    def connect(self):
        # Auto-discover device on first connection
        if (self.MacAddr is None):
            scanner = Scanner().withDelegate(DefaultDelegate())
            searchCount = 0
            #I have my wave plus and the pi zero W this runs on mounted directly across from each other in a standard hallway
            #It still fails at 0.1 and 50 more than once a day.
            while self.MacAddr is None and searchCount < 100:
                devices = scanner.scan(0.2)  # 0.1 seconds scan period
                searchCount += 1
                for dev in devices:
                    ManuData = dev.getValueText(255)
                    SN = parseSerialNumber(ManuData)
                    if (str(SN) == str(self.SN)):
                        self.MacAddr = dev.addr  # exits the while loop on next conditional check
                        break  # exit for loop

            if (self.MacAddr is None):
                print("ERROR - Could not find wave plus")
                sys.exit(1)

        # Connect to device
        if (self.periph is None):
            self.periph = Peripheral(self.MacAddr)
        if (self.curr_val_char is None):
            self.curr_val_char = self.periph.getCharacteristics(
                uuid=self.uuid)[0]
Beispiel #4
0
    def scan(match=None, duration=5, just_one=False, match_scan_entry=False):
        """This looks through any advertising btle devices for matching ones.

        *** Note you must run this as root ***

        match(scan_data) should return True if scan_data is from the device you're looking for.

            If no match function is provided, it is treated as always returning True (you want
                to see all devices that respond within duration).

            scan_data is a dict mapping description to value, unless match_scan_entry is True
                in which case scan_data is a btle ScanEntry object.

        Duration is how many seconds to scan before returning.

        If just_one is False, scans for the full duration and then
            returns a list of matching ScanEntry objects. (https://ianharvey.github.io/bluepy-doc/scanentry.html)

        If just_one is True, this returns the first match immediately (no list)
            or None after full duration timeout.

        Note (match==None and just_one==True) results in just the first device
            to respond being immediately returned.
        """
        scanner = Scanner().withDelegate(DefaultDelegate())
        scanner.clear()
        scanner.start()
        if not just_one:
            found = []
        try:
            for i in range(max(int(duration * 10),
                               1)):  # Break duration into 10ths
                scanner.process(
                    0.1)  # Handle incoming messages for 1/10th of a second...
                devices = scanner.getDevices()
                for dev in devices:
                    if debug:
                        BtleDevice.dump_scan_entry(dev)
                    if match_scan_entry:
                        params = dev
                    else:
                        params = {
                            name: val
                            for tag, name, val in dev.getScanData()
                        }
                    if match is None or match(params):
                        if just_one:
                            return dev
                        else:
                            found.append(dev)
                scanner.clear()
        finally:
            scanner.stop()

        if just_one:
            return None
        return found
 def connect(self):
     scanner     = Scanner().withDelegate(DefaultDelegate())
     # This Scanner must be an external function that scans the Bluetooth for a device
     self.periph = Peripheral(BTAddress)
     self.datetime_char     = self.periph.getCharacteristics(uuid=self.UUID_DATETIME)[0]
     self.humidity_char     = self.periph.getCharacteristics(uuid=self.UUID_HUMIDITY)[0]
     self.temperature_char  = self.periph.getCharacteristics(uuid=self.UUID_TEMPERATURE)[0]
     self.radon_st_avg_char = self.periph.getCharacteristics(uuid=self.UUID_RADON_ST_AVG)[0]
     self.radon_lt_avg_char = self.periph.getCharacteristics(uuid=self.UUID_RADON_LT_AVG)[0]
Beispiel #6
0
    def getTag(self):
        """Scans for BT LE devices and returns the choosen keywords"""
        self.count = 0
        scanner = Scanner().withDelegate(DefaultDelegate())
        devices = scanner.scan(self.scanTimeout)
        for dev in devices:
            if dev.addr == self.address.lower():
                self.count = 1

        if self.count > 0:
            self.count = 0
            return self.found
        else:
            return self.missing
    def connect(self):
        # Auto-discover device on first connection
        if (self.MacAddr is None):
            scanner     = Scanner().withDelegate(DefaultDelegate())
            searchCount = 0
            while self.MacAddr is None and searchCount < 50:
                devices      = scanner.scan(0.1) # 0.1 seconds scan period
                searchCount += 1
                for dev in devices:
                    ManuData = dev.getValueText(255)
                    if ManuData is not None:
                        SN = parseSerialNumber(ManuData)
                        if (SN == self.SN):
                            self.MacAddr = dev.addr # exits the while loop on next conditional check
                    else:
                        self.MacAddr = None
                    break # exit for loop
            
            if (self.MacAddr is None):
                print("ERROR: Could not find device.")
                print("GUIDE: (1) Please verify the serial number.")
                print("       (2) Ensure that the device is advertising.")
                print("       (3) Retry connection.")
                print("       (4) Try putting the device closer")
                if (os.path.isfile('/tmp/airthingswave.status.json')):
                    print("Temporary could not connect")
                else:
                    # create temp file
                    data = {
		           "humidity": 0,
		           "radon_st_avg": 0,
		           "radon_lt_avg": 0,
		           "temperature": 0,
		           "pressure": 0,
		           "CO2_lvl": 0,
		           "VOC_lvl": 0
		     }
                    with open('/tmp/airthingswave.status.json', 'wb') as f:
                        json.dump(data, codecs.getwriter('utf-8')(f), sort_keys = True, indent = 4, ensure_ascii=False)
                sys.exit(1)
        
        # Connect to device
        if (self.periph is None):
            self.periph = Peripheral(self.MacAddr)
        if (self.curr_val_char is None):
            self.curr_val_char = self.periph.getCharacteristics(uuid=self.uuid)[0]
    def search(self):
        # Auto-discover device on first connection
        scanner = Scanner().withDelegate(DefaultDelegate())
        search_count = 0
        while search_count < MAX_SEARCH_COUNT:
            devices = scanner.scan(SCAN_TIMEOUT)
            search_count += 1
            for dev in devices:
                manu_data = dev.getValueText(255)
                sn = parse_serial_number(manu_data)
                if sn == self.sn:
                    return dev.addr

        # Device not found after MAX_SEARCH_COUNT
        print(
            "ERROR: Could not find device.",
            "GUIDE: (1) Please verify the serial number.",
            "       (2) Ensure that the device is advertising.",
            "       (3) Retry connection.",
            sep="\n",
        )
        sys.exit(1)
Beispiel #9
0
 def read(self):
     scanner = Scanner().withDelegate(DefaultDelegate())
     temp_flg = False
     humid_flg = False
     self.isExist = False
     retry_count = 3
     while not (temp_flg and humid_flg) and retry_count > 0:
         devices = scanner.scan(7.0)
         for dev in devices:
             if dev.addr == self.address:
                 self.isExist = True
                 self.rssi = dev.rssi
                 (adtype, desc, value) = dev.getScanData()[2]
                 data = value[12:]
                 if data[0] == "1" and temp_flg == False:
                     temp_flg = True
                     self.temperature = self.readTemperature(data)
                 elif data[0] == "2" and humid_flg == False:
                     humid_flg = True
                     self.humidity = self.readHumidity(data)
         if not self.isExist:
             retry_count -= 1
Beispiel #10
0
    def scan(self):
        scanner = Scanner().withDelegate(DefaultDelegate())
        deviceFound = False
        searchCount = 0
        while deviceFound is False and searchCount < 50:
            devices = scanner.scan(0.1)  # 0.1 seconds scan period
            searchCount += 1
            for dev in devices:
                ManuData = dev.getValueText(255)
                SN = parseSerialNumber(ManuData)
                if (SN == SerialNumber):
                    MacAddr = dev.addr
                    deviceFound = True  # exits the while loop on next conditional check
                    break  # exit for loop

        if (deviceFound is not True):
            print "ERROR: Could not find device."
            print "GUIDE: (1) Please verify the serial number. (2) Ensure that the device is advertising. (3) Retry connection."
            sys.exit(1)
        else:
            self.mac_addr = MacAddr
            print "Found Wave Mac address %s" % (MacAddr)
    def connect(self):
        scanner = Scanner().withDelegate(DefaultDelegate())
        deviceFound = False
        searchCount = 0
        while deviceFound is False and searchCount < 50:
            devices = scanner.scan(0.1)  # 0.1 seconds scan period
            searchCount += 1
            for dev in devices:
                ManuData = dev.getValueText(255)
                SN = parseSerialNumber(ManuData)
                if (SN == SerialNumber):
                    MacAddr = dev.addr
                    deviceFound = True  # exits the while loop on next conditional check
                    break  # exit for loop

        if (deviceFound is not True):
            print "ERROR: Could not find device."
            print "GUIDE: (1) Please verify the serial number. (2) Ensure that the device is advertising. (3) Retry connection."
            sys.exit(1)
        else:
            self.periph = Peripheral(MacAddr)
            self.curr_val_char = self.periph.getCharacteristics(
                uuid=self.uuid)[0]
Beispiel #12
0
    def connect(self):
        # Check if device is already known (from scanning another device)
        if self.mac_addr is None and self.sn in WavePlus.sn2addr:
            self.mac_addr = WavePlus.sn2addr[self.sn]
            print("  Device {0} previously found, MAC address={1}".format(
                self.sn, self.mac_addr),
                  file=logf)

        # Auto-discover device on first connection
        if self.mac_addr is None:
            scanner = Scanner().withDelegate(DefaultDelegate())
            searchCount = 0
            while self.mac_addr is None and searchCount < 50:
                devices = scanner.scan(0.1)  # 0.1 seconds scan period
                searchCount += 1
                for dev in devices:
                    ManuData = dev.getValueText(255)
                    sn = self.parse_serial_number(ManuData)
                    if sn is not None and sn not in WavePlus.sn2addr:
                        WavePlus.sn2addr[sn] = dev.addr

                    # Serial number has been found. Register the other devices
                    if sn == self.sn:
                        self.mac_addr = dev.addr

            if self.mac_addr is None:
                raise ConnectionError("Could not find device " + self.sn)

            print("  Device {0} found, MAC address={1}".format(
                self.sn, self.mac_addr),
                  file=logf)

        # Connect to device
        if self.periph is None:
            self.periph = Peripheral(self.mac_addr)
        if self.val_char is None:
            self.val_char = self.periph.getCharacteristics(uuid=self.uuid)[0]
Beispiel #13
0
def scanForDevices():
	scanner = Scanner().withDelegate(DefaultDelegate())#ScanDelegate())
	devices = scanner.scan(4.0)
	return devices;
 def __init__(self, timeout: float = 10.0):
     self.scanner = Scanner().withDelegate(DefaultDelegate())
     self.timeout = timeout
Beispiel #15
0
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from bluepy.btle import Scanner, DefaultDelegate

scan_delegate = DefaultDelegate()

scanner = Scanner().withDelegate(scan_delegate)
devices = scanner.scan(10.0)

tbs_trackers = {}

for dev in devices:
    for data in dev.getScanData():
        if 'TBSRT' in data[2]:
            name = data[2].replace('\x00', '')
            tbs_trackers[name] = {'addr': dev.addr, 'rssi': dev.rssi}

for item in tbs_trackers:
    addr = tbs_trackers.get(item).get('addr')
    rssi = tbs_trackers.get(item).get('rssi')
Beispiel #16
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from bluepy.btle import Scanner, DefaultDelegate

scanner = Scanner().withDelegate(DefaultDelegate())
devices = scanner.scan(10.0)
target = "xx:xx:xx:xx:xx:xx"

for dev in devices:
    if dev.addr == target:
        print("Device %s (%s), RSSI=%d dB" %
              (dev.addr, dev.addrType, dev.rssi))
        (adtype, desc, value) = dev.getScanData()[2]
        data = value[12:]
        if data[0] == "1":
            print(data[1:])
            data = int(data[1:], 16)
            frac = float(data & 127) / 128.0
            exp = (data >> 7) & 15
            sign = (data >> 11) & 1
            sign = -1 if sign == 1 else 1
            if exp == 0:
                if frac == 0:
                    result = 0
                else:
                    result = frac / 64.0 * sign
            elif not exp == 15:
                result = (1 + frac) * 2**(exp - 7) * sign
            else:
                result = 0