Example #1
0
    def __init__(self, hass, devices, bt_device_id):
        """Construct interface object."""
        self.hass = hass

        # List of beacons to monitor
        self.devices = devices
        # Number of the bt device (hciX)
        self.bt_device_id = bt_device_id

        def callback(bt_addr, _, packet, additional_info):
            """Handle new packets."""
            self.process_packet(
                additional_info["namespace"],
                additional_info["instance"],
                packet.temperature,
            )

        from beacontools import (  # pylint: disable=import-error
            BeaconScanner, EddystoneFilter, EddystoneTLMFrame,
        )

        device_filters = [
            EddystoneFilter(d.namespace, d.instance) for d in devices
        ]

        self.scanner = BeaconScanner(callback, bt_device_id, device_filters,
                                     EddystoneTLMFrame)
        self.scanning = False
Example #2
0
def _start_scanner(enabled_providers: list, timeout_seconds: int,
                   simulate_beacons: bool, console_log: bool):
    if simulate_beacons:
        threading.Thread(name='background',
                         target=_start_beacon_simulation).start()
    else:
        scanner = BeaconScanner(_beacon_callback)
        scanner.start()
        print("...started: Tilt scanner")

    print("Ready!  Listening for beacons")
    start_time = time.time()
    end_time = start_time + timeout_seconds

    last_scanner_reset = time.time()
    time_to_reset_scanner = last_scanner_reset + 60

    while True:
        _handle_pitch_queue(enabled_providers, console_log)
        if time.time() > time_to_reset_scanner:
            last_scanner_reset = time.time()
            time_to_reset_scanner = last_scanner_reset + 60
            scanner.end()
            scanner = BeaconScanner(_beacon_callback)
            scanner.start()
            print("...restarted: Tilt scanner")

        # check timeout
        if timeout_seconds:
            current_time = time.time()
            if current_time > end_time:
                return  # stop
    def __init__(self, hass, devices, bt_device_id):
        """Construct interface object."""
        self.hass = hass

        # List of beacons to monitor
        self.devices = devices
        # Number of the bt device (hciX)
        self.bt_device_id = bt_device_id

        def callback(bt_addr, _, packet, additional_info):
            """Handle new packets."""
            temperature = struct.unpack('<h', struct.pack('>H', packet.temperature))[0] / 256
            self.process_packet(
                additional_info['namespace'] if additional_info else None, additional_info['instance'] if additional_info else None, bt_addr,
                temperature)

        # pylint: disable=import-error
        from beacontools import (
            BeaconScanner, BtAddrFilter, EddystoneFilter, EddystoneTLMFrame)
        device_filters = [(BtAddrFilter(d.mac) if d.mac else EddystoneFilter(d.namespace, d.instance))
                          for d in devices]

        self.scanner = BeaconScanner(
            callback, bt_device_id, device_filters, EddystoneTLMFrame)
        self.scanning = False
Example #4
0
    def start(self):
        def callback(bt_addr, rssi, packet, additional_info):
            self.scanner._mon.toggle_scan(False)
            sg = additional_info['minor'] / 1000
            t_f = additional_info['major']
            self.grav = 135.997 * (sg**3) - 630.272 * (
                sg**2) + 1111.14 * sg - 616.868
            self.temp = (t_f - 32) * 5 / 9.

        self.scanner = BeaconScanner(callback,
                                     packet_filter=IBeaconAdvertisement)

        async def run():
            devices = await discover()

        loop = asyncio.get_event_loop()
        loop.run_until_complete(run())

        self.scanner.start()

        def _run():
            while True:
                time.sleep(self.period)
                self.scanner._mon.toggle_scan(True)

        threading.Thread(target=_run).start()
Example #5
0
 def test_process_packet_dev_filter4(self):
     """Test processing of a packet and callback execution with cj Monitor device filter."""
     callback = MagicMock()
     scanner = BeaconScanner(callback, device_filter=CJMonitorFilter())
     pkt = b"\x04\x3e\x29\x02\x01\x00\x00\x43\x56\x5b\x57\x0b\x00\x1d" \
           b"\x02\x01\x06\x05\x02\x1a\x18\x00\x18" \
           b"\x09\xff\x72\x04\xfe\x10\xbc\x0c\x37\x59" \
           b"\x09\x09\x4d\x6f\x6e\x20\x35\x36\x34\x33\xaa"
     scanner._mon.process_packet(pkt)
     self.assertEqual(1, callback.call_count)
     args = callback.call_args[0]
     self.assertEqual("00:0b:57:5b:56:43", args[0])
     self.assertEqual(-86, args[1])
     self.assertIsInstance(args[2], CJMonitorAdvertisement)
     self.assertEqual(
         'CJMonitorAdvertisement<name: Mon 5643, temp: 32.6,humidity: 55, light: 160>',
         str(args[2]))
     self.assertEqual(
         {
             "beacon_type": CJ_TEMPHUM_TYPE,
             "company_id": CJ_MANUFACTURER_ID,
             'name': 'Mon 5643',
             'light': 159.9,
             "temperature": 32.6,
             "humidity": 55
         }, args[3])
     # Test same packet with different beacon type, should be ignored.
     scanner = BeaconScanner(
         callback, device_filter=CJMonitorFilter(beacon_type=4351))
     scanner._mon.process_packet(pkt)
     self.assertEqual(1, callback.call_count)
Example #6
0
class Monitor(object):
    """Continously scan for BLE advertisements."""
    def __init__(self, hass, devices, bt_device_id):
        """Construct interface object."""
        self.hass = hass

        # list of beacons to monitor
        self.devices = devices
        # number of the bt device (hciX)
        self.bt_device_id = bt_device_id

        def callback(bt_addr, _, packet, additional_info):
            """Callback for new packets."""
            self.process_packet(additional_info['namespace'],
                                additional_info['instance'],
                                packet.temperature)

        # pylint: disable=import-error
        from beacontools import (BeaconScanner, EddystoneFilter,
                                 EddystoneTLMFrame)
        # Create a device filter for each device
        device_filters = [
            EddystoneFilter(d.namespace, d.instance) for d in devices
        ]

        self.scanner = BeaconScanner(callback, bt_device_id, device_filters,
                                     EddystoneTLMFrame)
        self.scanning = False

    def start(self):
        """Continously scan for BLE advertisements."""
        if not self.scanning:
            self.scanner.start()
            self.scanning = True
        else:
            _LOGGER.debug("Warning: start() called, but scanner is already"
                          " running")

    def process_packet(self, namespace, instance, temperature):
        """Assign temperature to hass device."""
        _LOGGER.debug("Received temperature for <%s,%s>: %d", namespace,
                      instance, temperature)

        for dev in self.devices:
            if dev.namespace == namespace and dev.instance == instance:
                if dev.temperature != temperature:
                    dev.temperature = temperature
                    dev.schedule_update_ha_state()

    def stop(self):
        """Signal runner to stop and join thread."""
        if self.scanning:
            _LOGGER.debug("Stopping...")
            self.scanner.stop()
            _LOGGER.debug("Stopped")
            self.scanning = False
        else:
            _LOGGER.debug("Warning: stop() called but scanner was not"
                          " running.")
class Monitor(object):
    """Continously scan for BLE advertisements."""

    def __init__(self, hass, devices, bt_device_id):
        """Construct interface object."""
        self.hass = hass

        # list of beacons to monitor
        self.devices = devices
        # number of the bt device (hciX)
        self.bt_device_id = bt_device_id

        def callback(bt_addr, _, packet, additional_info):
            """Callback for new packets."""
            self.process_packet(additional_info['namespace'],
                                additional_info['instance'],
                                packet.temperature)

        # pylint: disable=import-error
        from beacontools import (BeaconScanner, EddystoneFilter,
                                 EddystoneTLMFrame)
        # Create a device filter for each device
        device_filters = [EddystoneFilter(d.namespace, d.instance)
                          for d in devices]

        self.scanner = BeaconScanner(callback, bt_device_id, device_filters,
                                     EddystoneTLMFrame)
        self.scanning = False

    def start(self):
        """Continously scan for BLE advertisements."""
        if not self.scanning:
            self.scanner.start()
            self.scanning = True
        else:
            _LOGGER.debug("Warning: start() called, but scanner is already"
                          " running")

    def process_packet(self, namespace, instance, temperature):
        """Assign temperature to hass device."""
        _LOGGER.debug("Received temperature for <%s,%s>: %d",
                      namespace, instance, temperature)

        for dev in self.devices:
            if dev.namespace == namespace and dev.instance == instance:
                if dev.temperature != temperature:
                    dev.temperature = temperature
                    dev.schedule_update_ha_state()

    def stop(self):
        """Signal runner to stop and join thread."""
        if self.scanning:
            _LOGGER.debug("Stopping...")
            self.scanner.stop()
            _LOGGER.debug("Stopped")
            self.scanning = False
        else:
            _LOGGER.debug("Warning: stop() called but scanner was not"
                          " running.")
class Monitor:
    """Continuously scan for BLE advertisements."""

    def __init__(self, hass, devices, bt_device_id):
        """Construct interface object."""
        self.hass = hass

        # List of beacons to monitor
        self.devices = devices
        # Number of the bt device (hciX)
        self.bt_device_id = bt_device_id

        def callback(bt_addr, _, packet, additional_info):
            """Handle new packets."""
            self.process_packet(
                additional_info["namespace"],
                additional_info["instance"],
                packet.temperature,
            )

        device_filters = [EddystoneFilter(d.namespace, d.instance) for d in devices]

        self.scanner = BeaconScanner(
            callback, bt_device_id, device_filters, EddystoneTLMFrame
        )
        self.scanning = False

    def start(self):
        """Continuously scan for BLE advertisements."""
        if not self.scanning:
            self.scanner.start()
            self.scanning = True
        else:
            _LOGGER.debug("start() called, but scanner is already running")

    def process_packet(self, namespace, instance, temperature):
        """Assign temperature to device."""
        _LOGGER.debug(
            "Received temperature for <%s,%s>: %d", namespace, instance, temperature
        )

        for dev in self.devices:
            if (
                dev.namespace == namespace
                and dev.instance == instance
                and dev.temperature != temperature
            ):
                dev.temperature = temperature
                dev.schedule_update_ha_state()

    def stop(self):
        """Signal runner to stop and join thread."""
        if self.scanning:
            _LOGGER.debug("Stopping")
            self.scanner.stop()
            _LOGGER.debug("Stopped")
            self.scanning = False
        else:
            _LOGGER.debug("stop() called but scanner was not running")
class Monitor:
    """Continuously scan for BLE advertisements."""

    def __init__(self, hass, devices, bt_device_id):
        """Construct interface object."""
        self.hass = hass

        # List of beacons to monitor
        self.devices = devices
        # Number of the bt device (hciX)
        self.bt_device_id = bt_device_id

        def callback(bt_addr, _, packet, additional_info):
            """Handle new packets."""
            temperature = struct.unpack('<h', struct.pack('>H', packet.temperature))[0] / 256
            self.process_packet(
                additional_info['namespace'] if additional_info else None, additional_info['instance'] if additional_info else None, bt_addr,
                temperature)

        # pylint: disable=import-error
        from beacontools import (
            BeaconScanner, BtAddrFilter, EddystoneFilter, EddystoneTLMFrame)
        device_filters = [(BtAddrFilter(d.mac) if d.mac else EddystoneFilter(d.namespace, d.instance))
                          for d in devices]

        self.scanner = BeaconScanner(
            callback, bt_device_id, device_filters, EddystoneTLMFrame)
        self.scanning = False

    def start(self):
        """Continuously scan for BLE advertisements."""
        if not self.scanning:
            self.scanner.start()
            self.scanning = True
        else:
            _LOGGER.debug(
                "start() called, but scanner is already running")

    def process_packet(self, namespace, instance, mac, temperature):
        """Assign temperature to device."""
        _LOGGER.debug("Received temperature for <%s,%s,%s>: %d",
                      namespace, instance, mac, temperature)

        for dev in self.devices:
            if (dev.namespace and dev.instance and dev.namespace == namespace and dev.instance == instance) or (dev.mac and dev.mac == mac):
                if dev.temperature != temperature:
                    dev.temperature = temperature
                    dev.schedule_update_ha_state()

    def stop(self):
        """Signal runner to stop and join thread."""
        if self.scanning:
            _LOGGER.debug("Stopping...")
            self.scanner.stop()
            _LOGGER.debug("Stopped")
            self.scanning = False
        else:
            _LOGGER.debug(
                "stop() called but scanner was not running")
Example #10
0
def _start_scanner(enabled_providers: list, timeout_seconds: int,
                   simulate_beacons: bool, console_log: bool):
    if simulate_beacons:
        # Set daemon true so this thread dies when the parent process/thread dies
        threading.Thread(name='background',
                         target=_start_beacon_simulation,
                         daemon=True).start()
    else:
        scanner = BeaconScanner(_beacon_callback,
                                packet_filter=IBeaconAdvertisement)
        scanner.start()
        signal.signal(signal.SIGTERM, _trigger_graceful_termination)
        print("...started: Tilt scanner")

    print("Ready!  Listening for beacons")
    start_time = time.time()
    end_time = start_time + timeout_seconds
    try:
        while True:
            _handle_pitch_queue(enabled_providers, console_log)
            # check timeout
            if timeout_seconds:
                current_time = time.time()
                if current_time > end_time:
                    return  # stop
    except KeyboardInterrupt as e:
        if not simulate_beacons:
            scanner.stop()
        print("...stopped: Tilt Scanner (keyboard interrupt)")
    except Exception as e:
        if not simulate_beacons:
            scanner.stop()
        print("...stopped: Tilt Scanner ({})".format(e))
Example #11
0
 def test_process_packet_exposure_notification_filter(self):
     """Test processing of a exposure notification with device filter."""
     callback = MagicMock()
     scanner = BeaconScanner(
         callback,
         device_filter=ExposureNotificationFilter(
             identifier="0d3b4f65584c582160571dd19010d41c"))
     # correct identifier
     pkt = b"\x04\x3e\x2b\x02\x01\x03\x01\xe1\xac\xca\x3d\xea\x0d\x1f\x02\x01\x1a\x03\x03\x6f" \
           b"\xfd\x17\x16\x6f\xfd\x0d\x3b\x4f\x65\x58\x4c\x58\x21\x60\x57\x1d\xd1\x90\x10\xd4" \
           b"\x1c\x26\x60\xee\x34\xd1"
     # different identifier
     pkt2 = b"\x04\x3e\x2b\x02\x01\x03\x01\xe1\xac\xca\x3d\xea\x0d\x1f\x02\x01\x1a\x03\x03\x6f" \
            b"\xfd\x17\x16\x6f\xfd\x0d\x3b\x40\x65\x58\x4c\x58\x21\x60\x57\x1d\xd1\x90\x10\xd4" \
            b"\x1c\x26\x60\xee\x34\xd1"
     scanner._mon.process_packet(pkt)
     scanner._mon.process_packet(pkt2)
     self.assertEqual(callback.call_count, 1)
     args = callback.call_args[0]
     self.assertEqual(args[0], "0d:ea:3d:ca:ac:e1")
     self.assertEqual(args[1], -47)
     self.assertIsInstance(args[2], ExposureNotificationFrame)
     self.assertEqual(
         args[3], {
             "identifier": "0d3b4f65584c582160571dd19010d41c",
             "encrypted_metadata": b"\x26\x60\xee\x34"
         })
    def __init__(self, hass, devices, bt_device_id):
        """Construct interface object."""
        self.hass = hass

        # list of beacons to monitor
        self.devices = devices
        # number of the bt device (hciX)
        self.bt_device_id = bt_device_id

        def callback(bt_addr, _, packet, additional_info):
            """Callback for new packets."""
            self.process_packet(additional_info['namespace'],
                                additional_info['instance'],
                                packet.temperature)

        # pylint: disable=import-error
        from beacontools import (BeaconScanner, EddystoneFilter,
                                 EddystoneTLMFrame)
        # Create a device filter for each device
        device_filters = [EddystoneFilter(d.namespace, d.instance)
                          for d in devices]

        self.scanner = BeaconScanner(callback, bt_device_id, device_filters,
                                     EddystoneTLMFrame)
        self.scanning = False
Example #13
0
 def test_multiple_filters2(self):
     callback = MagicMock()
     scanner = BeaconScanner(
         callback,
         device_filter=[
             EstimoteFilter(identifier="47a038d5eb032640",
                            protocol_version=2),
             EddystoneFilter(instance="000000000001")
         ],
         packet_filter=[EstimoteTelemetryFrameB, EddystoneUIDFrame])
     pkt = b"\x41\x3e\x41\x02\x01\x03\x01\x35\x94\xef\xcd\xd6\x1c\x19\x02\x01\x04\x03\x03\x9a"\
           b"\xfe\x17\x16\x9a\xfe\x22\x47\xa0\x38\xd5\xeb\x03\x26\x40\x01\xff\xff\xff\xff\x49"\
           b"\x25\x66\xbc\x2e\x50\xdd"
     scanner._mon.process_packet(pkt)
     pkt = b"\x41\x3e\x41\x02\x01\x03\x01\x35\x94\xef\xcd\xd6\x1c\x19\x02\x01\x04\x03\x03\x9a"\
           b"\xfe\x17\x16\x9a\xfe\x12\x47\xa0\x38\xd5\xeb\x03\x26\x40\x00\x00\x01\x41\x44\x47"\
           b"\xf0\x01\x00\x00\x00\xdd"
     scanner._mon.process_packet(pkt)
     pkt = b"\x41\x3e\x41\x02\x01\x03\x01\x35\x94\xef\xcd\xd6\x1c\x19\x02\x01\x06\x03\x03\xaa"\
           b"\xfe\x11\x16\xaa\xfe\x00\xe3\x12\x34\x56\x78\x90\x12\x34\x67\x89\x01\x00\x00\x00"\
           b"\x00\x00\x01\x00\x00\xdd"
     scanner._mon.process_packet(pkt)
     pkt = b"\x41\x3e\x41\x02\x01\x03\x01\x35\x94\xef\xcd\xd6\x1c\x19\x02\x01\x06\x03\x03\xaa"\
           b"\xfe\x11\x16\xaa\xfe\x00\xe3\x12\x34\x56\x78\x90\x12\x34\x67\x89\x01\x00\x00\x00"\
           b"\x00\x00\x02\x00\x00\xdd"
     scanner._mon.process_packet(pkt)
     pkt = b"\x41\x3e\x41\x02\x01\x03\x01\x35\x94\xef\xcd\xd6\x1c\x19\x02\x01\x06\x03\x03\xaa"\
           b"\xfe\x11\x16\xaa\xfe\x00\xe3\x12\x34\x56\x78\x90\x12\x34\x67\x89\x01\x00\x00\x00"\
           b"\x00\x00\x01\x00\x00\xdd"
     scanner._mon.process_packet(pkt)
     self.assertEqual(callback.call_count, 3)
Example #14
0
async def main():
    try:
        global HUB_MANAGER
        print("\nPython %s\n" % sys.version)

        HUB_MANAGER = await create_hubmanager()

        try:
            scanner = BeaconScanner(callback, )
            scanner.start()
            print("BLE thread started")

        except:
            print("Error accessing bluetooth device...")
            sys.exit(1)
    except KeyboardInterrupt:
        print("Module stopped")
Example #15
0
 def test_process_packet_dev_filter2(self):
     """Test processing of a packet and callback execution."""
     callback = MagicMock()
     scanner = BeaconScanner(callback, device_filter=EddystoneFilter(instance="000000000001"))
     pkt = b"\x41\x3e\x41\x02\x01\x03\x01\x35\x94\xef\xcd\xd6\x1c\x19\x02\x01\x06\x03\x03\xaa"\
           b"\xfe\x11\x16\xaa\xfe\x20\x00\x0b\x18\x13\x00\x00\x00\x14\x67\x00\x00\x2a\xc4\xe4"
     scanner._mon.process_packet(pkt)
     callback.assert_not_called()
Example #16
0
def start_scanner(url, name, private_key):
    logger.info("Starting scanner")
    scanner = BeaconScanner(_beacon_callback,
                            packet_filter=IBeaconAdvertisement)
    scanner.start()
    logger.info("Scanner started")

    while True:
        data = tilt_queue.get()
        timestamp = data['time'].isoformat()
        celsius = round((data['temp'] - 32) * 5.0 / 9.0, 1)
        gravity = round(data['gravity'] * .001, 4)

        logger.info(
            "Beer %s, timestamp %s, temp F %d, temp C %1.2f, gravity %1.4f" %
            (name, timestamp, data['temp'], celsius, gravity))

        payload = dict()

        payload['name'] = name
        payload['timestamp'] = timestamp
        payload['fahrenheit'] = data['temp']
        payload['celsius'] = celsius
        payload['gravity'] = gravity
        payload['signature'] = sign_data(
            private_key,
            json.dumps(payload).encode('utf-8')).decode("utf-8")

        payload_json = json.dumps(payload)

        logger.debug("Sending to %s with headers %s the payload %s" %
                     (url, headers, payload_json))

        try:
            response = requests.post(url,
                                     data=payload_json,
                                     headers=headers,
                                     timeout=10)
            response.raise_for_status()
        except HTTPError as http_err:
            logger.exception(http_err)
        except Exception as err:
            logger.exception(err)
        else:
            logger.info("Payload delivered!")
Example #17
0
 def test_process_packet_filter_bad(self):
     """Test processing of a packet and callback execution with packet filter."""
     callback = MagicMock()
     scanner = BeaconScanner(callback, packet_filter=EddystoneTLMFrame)
     pkt = b"\x41\x3e\x41\x02\x01\x03\x01\x35\x94\xef\xcd\xd6\x1c\x19\x02\x01\x06\x03\x03\xaa"\
           b"\xfe\x11\x16\xaa\xfe\x00\xe3\x12\x34\x56\x78\x90\x12\x34\x67\x89\x01\x00\x00\x00"\
           b"\x00\x00\x01\x00\x00\xdd"
     scanner._mon.process_packet(pkt)
     callback.assert_not_called()
Example #18
0
 def test_process_packet_bad_packet(self):
     """Test processing of a packet and callback execution with a bad packet."""
     callback = MagicMock()
     scanner = BeaconScanner(
         callback,
         device_filter=EddystoneFilter(namespace="12345678901234678901"),
         packet_filter=EddystoneUIDFrame)
     pkt = b"\x41\x3e\x41\x02\x01\x03"
     scanner._mon.process_packet(pkt)
     callback.assert_not_called()
Example #19
0
def _start_scanner(enabled_providers: list, timeout_seconds: int, simulate_beacons: bool, console_log: bool):
    if simulate_beacons:
        threading.Thread(name='background', target=_start_beacon_simulation).start()
    else:
        scanner = BeaconScanner(_beacon_callback, packet_filter=IBeaconAdvertisement)
        scanner.start()
        print("...started: Tilt scanner")

    print("Ready!  Listening for beacons")
    start_time = time.time()
    end_time = start_time + timeout_seconds
    while True:
        time.sleep(0.01)
        _handle_pitch_queue(enabled_providers, console_log)
        # check timeout
        if timeout_seconds:
            current_time = time.time()
            if current_time > end_time:
                return  # stop
def scan_ibeacons():
    # callback to show beacons read
    def callback(bt_addr, rssi, packet, additional_info):
        print("[ MAC: {} | RSSI: {} ] - {}".format(bt_addr, rssi, packet))

    # intance the parser
    parser = argparse.ArgumentParser()
    # parse uuid argument
    parser.add_argument(
        '--uuid',
        action='store',
        dest='uuid',
        help='iBeacon UUID. Def: {}'.format(DEFAULT_BEACON_UUID))
    # parse scan_time argument
    parser.add_argument('--time',
                        action='store',
                        dest='scan_time',
                        help='Scan time. Def: {}'.format(DEFAULT_TIME_TO_SCAN))
    # get result of parse arguments in args
    args = parser.parse_args()
    uuid = args.uuid if args.uuid is not None else DEFAULT_BEACON_UUID
    scan_time = args.scan_time if args.scan_time is not None else DEFAULT_TIME_TO_SCAN
    # scan for all iBeacon advertisements from beacons with the specified uuid
    scanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid=uuid))
    # start scanning
    print("Starting to scan beacons with UUID={} for {} seconds".format(
        uuid, scan_time))
    scanner.start()
    time.sleep(scan_time)
    scanner.stop()
    print("Scan beacons finished!")
    def _scan(self):
        """ This function scans for iBeacon packets, save them in a list, 
        order packets by RSSI and update near beacons attrs accordingly """
        def _scans_callback(bt_addr, rssi, packet, additional_info):
            beacon = IBeacon(bt_addr, packet.uuid, packet.major, packet.minor,
                             packet.tx_power, rssi)
            if not self._is_beacon_in_list(beacon):
                self._beacons_list.append(beacon)

        while (self._run_flag):
            # clear beacon list
            self._beacons_list = []
            # instance the scanner
            scanner = BeaconScanner(
                _scans_callback,
                device_filter=IBeaconFilter(uuid=self._uuid_filter))
            # perform the scan
            scanner.start()
            time.sleep(self._scan_tick)
            scanner.stop()
            # order the beacons list by RSSI (Power received)
            if len(self._beacons_list) >= 1:
                self._order_beacons_list()
                self._last_nearest_beacon = self._nearest_beacon
                self._nearest_beacon = self._beacons_list[0]
                logging.info("Nearest beacon: {}".format(self._nearest_beacon))
            else:
                self._last_nearest_beacon = self._nearest_beacon
                self._nearest_beacon = None
                logging.info("No beacons found in this scan")
            # evaluate if nearest beacon has changes, if so, invoke changes callback
            if self._check_if_nearest_beacon_changes():
                self._invoke_changes_callback()
Example #22
0
def pitch_main():
    start_message()
    # add any webhooks defined in config
    add_webhook_providers(config)
    # Start cloud providers
    print("Starting...")
    for provider in all_providers:
        if provider.enabled():
            enabled_providers.append(provider)
            provider_start_message = provider.start()
            if not provider_start_message:
                provider_start_message = ''
            print("...started: {} {}".format(provider, provider_start_message))

    if config.simulate_beacons:
        threading.Thread(name='background', target=simulate_beacons).start()
    else:
        scanner = BeaconScanner(beacon_callback)
        scanner.start()
        print("...started: Tilt scanner")

    print("Ready!  Listening for beacons")
Example #23
0
    def init(self):
        if not self.communicate:
            scanner_callback = proximity_callback
        else:
            publisher = MQTTPublisher()
            scanner_callback = functools.partial(communicate_callback,
                                                 publisher)

        self.scanner = BeaconScanner(
            scanner_callback,
            scan_parameters={"address_type": BluetoothAddressType.PUBLIC})

        self.start_scan()
Example #24
0
 def test_process_packet(self):
     """Test processing of a packet and callback execution."""
     callback = MagicMock()
     scanner = BeaconScanner(callback)
     pkt = b"\x41\x3e\x41\x02\x01\x03\x01\x35\x94\xef\xcd\xd6\x1c\x19\x02\x01\x06\x03\x03\xaa"\
           b"\xfe\x11\x16\xaa\xfe\x20\x00\x0b\x18\x13\x00\x00\x00\x14\x67\x00\x00\x2a\xc4\xe4"
     scanner._mon.process_packet(pkt)
     self.assertEqual(callback.call_count, 1)
     args = callback.call_args[0]
     self.assertEqual(args[0], "1c:d6:cd:ef:94:35")
     self.assertEqual(args[1], -28)
     self.assertIsInstance(args[2], EddystoneTLMFrame)
     self.assertEqual(args[3], None)
Example #25
0
 def test_exposure_notification(self):
     callback = MagicMock()
     scanner = BeaconScanner(callback,
                             packet_filter=[ExposureNotificationFrame])
     # Android and iOS seem to use slightly different packets
     android_pkt = b"\x04\x3E\x28\x02\x01\x03\x01\xBB\x7E\xB5\x2B\x86\x79\x1C\x03\x03\x6F\xFD\x17\x16"\
                   b"\x6F\xFD\x2C\xFB\x0D\xE0\x2B\x33\xD2\x0C\x5C\x27\x61\x12\x38\xE2\xD1\x07\x42\xB5"\
                   b"\x6E\xE5\xB8"
     scanner._mon.process_packet(android_pkt)
     ios_pkt = b"\x04\x3E\x2B\x02\x01\x03\x01\x08\xE6\xAE\x33\x0B\x3F\x1F\x02\x01\x1A\x03\x03\x6F"\
               b"\xFD\x17\x16\x6F\xFD\xE9\x32\xE8\xB0\x68\x8D\xFA\xEC\x00\x62\xB7\xD6\xD3\x5E\xEF"\
               b"\xB5\xEE\xAA\x91\xAC\xBA"
     scanner._mon.process_packet(ios_pkt)
     self.assertEqual(callback.call_count, 2)
Example #26
0
    def test_bad_arguments(self):
        """Test if wrong filters result in ValueError."""
        tests = [
            ([{"namespace" : "ABC"}], None),
            (None, EddystoneFilter()),
            (None, [EddystoneFilter()]),
            (EddystoneTLMFrame, []),
            ([EddystoneTLMFrame], None),
            ([EddystoneTLMFrame], [EddystoneFilter()]),
        ]

        for dev_filter, pkt_filter in tests:
            with self.assertRaises(ValueError):
                BeaconScanner(None, 0, dev_filter, pkt_filter)
Example #27
0
    def test_good_arguments(self):
        """Test if correct filters result in no exception."""
        tests = [
            (None, None),
            ([], []),
            ([EddystoneFilter()], None),
            (EddystoneFilter(), None),
            (None, EddystoneTLMFrame),
            (None, [EddystoneTLMFrame]),
            (EddystoneFilter(), [EddystoneTLMFrame]),
        ]

        for dev_filter, pkt_filter in tests:
            self.assertIsNotNone(BeaconScanner(None, 0, dev_filter, pkt_filter))
Example #28
0
def main():
    args = parser.parse_args()

    if args.config:
        save(args.config)

    # start MQTT client
    mqtt.setup()

    sensor_list = []

    for sensor in config.sensors:
        if sensor.type == 'dht22':
            s = DHT(sensor.pin, sensor.topic, sensor.name, 'sensor',
                    sensor.type)
        elif sensor.type == 'ibeacon':
            s = Scanner(sensor.name, sensor.topic, sensor.uuid,
                        sensor.away_timeout)
        elif sensor.type == 'switch':
            s = Switch(sensor.name, sensor.pin, sensor.topic)
        elif sensor.type == 'reed':
            s = ReedSwitch(sensor.name, sensor.pin, sensor.topic,
                           sensor.normally_open, sensor.get('device_type'))
        elif sensor.type == 'bme280':
            s = BME280(sensor.name, sensor.topic)
        elif sensor.type == 'hestiapi':
            s = HestiaPi(sensor.name,
                         sensor.topic,
                         sensor.heat_setpoint,
                         sensor.cool_setpoint,
                         dry_run=args.dry_run)
        else:
            logging.warn(
                'Sensor {} found in config, but was not setup.'.format(
                    sensor.name))
        if s:
            sensor_list.append(s)

    try:
        scanner = BeaconScanner(sensor_list[1].process_ble_update)
        scanner.start()
    except:
        logging.error("Beacon scanner did not start")

    try:
        while True:

            for sensor in sensor_list:
                sensor.callback()

            time.sleep(300)

    except:
        traceback.print_exc()
        mqtt.client.loop_stop()
        if scanner:
            scanner.stop()
Example #29
0
 def read_ble(self):
     scanner = BeaconScanner(
         self.read_callback,
         packet_filter=[EddystoneUIDFrame],
         device_filter=EddystoneFilter(namespace=self.uuid))
     scanner.start()
     print("Lendo beacon por {}'s".format(self.read_time))
     time.sleep(self.read_time)
     scanner.stop()
     return self.rssi_list
def read_ble(sleep_time=1, loops=2):
    for loop in range(0, loops):
        scanner = BeaconScanner(
            read_callback,
            device_filter=EddystoneFilter(namespace="edd1ebeac04e5defa017"),
            packet_filter=[EddystoneUIDFrame]
        )
        scanner.start()
        time.sleep(sleep_time)
        scanner.stop()
def main_Buletooth ():
    test = ly.Bluetooth()
    global data
    data = {}
    xd = []
    yd = []
    RSSIa = []
    RSSIb = []
    RSSIc = []
    plt.figure()

    while( 1 ):
        scanner = BeaconScanner(ly.scan_base)
        scanner.start()
        #将rssi值与mac地址分开
        flag = 1
        while( flag ):
            time.sleep(0.5)
            #print (data)
            """传入参数     待改正"""
            for add in data.keys():
                if add == u'10:01:12:ee:57:54':
                    RSSIa.append(data[add])
                    print("RSSIa=",len(RSSIa))
                    #print("RSSIa=",RSSIa)
                elif add == u'20:01:14:9c:57:54':
                    RSSIb.append(data[add])
                    print("RSSIb=",len(RSSIb))
                    #print("RSSIb=",RSSIb)
                else:
                    RSSIc.append(data[add])
                    print("RSSIc=",len(RSSIc))
                    #print("RSSIc=",RSSIc)
            if len(RSSIa) >= 20 and len(RSSIb) >= 20 and len(RSSIc) >= 20:
                flag = 0
                scanner.stop()
        ra = test.Gaussion_filter(RSSIa)
        rb = test.Gaussion_filter(RSSIb)
        rc = test.Gaussion_filter(RSSIc)
        #print(ra)
        #print(rb)
        #print(rc)
        r3 = test.RSSI_distance(ra)
        r1 = test.RSSI_distance(rb)
        r2 = test.RSSI_distance(rc)
        #print (r1)
        #print (r2)
        #print (r3)
        coordinate_D = test.fixed_point(r1,r2,r3)
        test.coordinate_system_data(coordinate_D)
        del RSSIa[:]
        del RSSIb[:]
        del RSSIc[:]
        data.clear()
 def run(self):
     while True:
         scanner = BeaconScanner(
             callback,
             device_filter=IBeaconFilter(
                 uuid='636f3f8f-6491-4bee-95f7-d8cc64a863b5')
         )  #"b9407f30-f5f8-466e-aff9-25556b57fe6d", major=30174, minor=5667)) #coconut2
         #my rpi beacon uuid 636f3f8f-6491-4bee-95f7-d8cc64a863b5
         scanner.start()
         time.sleep(5)
         scanner.stop()