def test_exception_in_with(self):
     """Test clean exit after exception."""
     bluetooth_if = BluetoothInterface(MockBackend)
     self.assertFalse(bluetooth_if.is_connected())
     with self.assertRaises(ValueError):
         with bluetooth_if.connect('abc'):
             raise ValueError('some test exception')
     self.assertFalse(bluetooth_if.is_connected())
    def test_context_manager_locking(self):
        """Test the usage of the with statement."""
        bluetooth_if = BluetoothInterface(MockBackend)
        self.assertFalse(bluetooth_if.is_connected())

        with bluetooth_if.connect('abc'):  # as connection:
            self.assertTrue(bluetooth_if.is_connected())

        self.assertFalse(bluetooth_if.is_connected())
Esempio n. 3
0
 def __init__(self, address, keepalive_interval, attempts, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.address = address
     self.keepalive_interval = keepalive_interval
     self.attempts = attempts
     self.interface = BluetoothInterface(BluepyBackend)
     self.queue = queue.Queue()
     self.failure_count = 0
     self.success_count = 0
     self.loop_count = 0
     self.empty_count = 0
    def __init__(self, mac, backend, cache_timeout=600, adapter='hci0'):
        """
        Initialize a Mi Flora Poller for the given MAC address.
        """

        self._mac = mac
        self._bt_interface = BluetoothInterface(backend, adapter)
        self._cache = None
        self._cache_timeout = timedelta(seconds=cache_timeout)
        self._last_read = None
        self._fw_last_read = None
        self.ble_timeout = 10
        self.lock = Lock()
Esempio n. 5
0
    def __init__(self, mac, backend, cache_timeout=600, retries=3, adapter='hci0'):
        """
        Initialize a Mi Temp Poller for the given MAC address.
        """

        self._mac = mac
        self._bt_interface = BluetoothInterface(backend, adapter=adapter)
        self._cache = None
        self._cache_timeout = timedelta(seconds=cache_timeout)
        self._last_read = None
        self._fw_last_read = None
        self.retries = retries
        self.ble_timeout = 10
        self.lock = Lock()
        self._firmware_version = None
        self.battery = None
Esempio n. 6
0
    def update_sensor(self):
        """
        Get data from device.

        This method reads the handle 0x003f that contains temperature, humidity
        and battery level.
        """
        # bt_interface = BluetoothInterface(self._backend, "hci0")
        bt_interface = BluetoothInterface(
            backend=self._backend, adapter="hci0")

        try:
            with bt_interface.connect(self._mac) as connection:
                raw = connection.read_handle(
                    0x003F)  # pylint: disable=no-member

            if not raw:
                raise BluetoothBackendException("Could not read 0x003f handle")

            raw_bytes = bytearray(raw)

            temp = int.from_bytes(raw_bytes[1:3], "little") / 10.0
            if temp >= 32768:
                temp = temp - 65535

            humidity = int(raw_bytes[4])
            battery = int(raw_bytes[9])

            self._temp = temp
            self._humidity = humidity
            self._battery = battery
            self._last_update = datetime.now()

            _LOGGER.debug("%s: Find temperature with value: %s",
                          self._mac, self._temp)
            _LOGGER.debug("%s: Find humidity with value: %s",
                          self._mac, self._humidity)
            _LOGGER.debug("%s: Find battery with value: %s",
                          self._mac, self._battery)
        except BluetoothBackendException:
            return
Esempio n. 7
0
#!/usr/bin/env python3

# aptitude install python3-pip libglib2.0-dev
# pip3 install btlewrap

import sys
from btlewrap.base import BluetoothInterface
from btlewrap.gatttool import GatttoolBackend

HANDLE_READ_BATTERY_LEVEL = 0x0018
HANDLE_READ_WRITE_SENSOR_DATA = 0x0010

class TempHumDelegate():
  def handleNotification(self, handle, data):
    print('Notification: handle=%s data=%s' % (handle, data))

mac = sys.argv[1]
print('MAC: %s' % mac)

bt_interface = BluetoothInterface(GatttoolBackend, adapter='hci0')
with bt_interface.connect(mac) as connection:
    res_battery = connection.read_handle(HANDLE_READ_BATTERY_LEVEL)
    battery = int(ord(res_battery))
    print('Battery: %s' % battery)

    connection.wait_for_notification(
            HANDLE_READ_WRITE_SENSOR_DATA,
            TempHumDelegate(),
            10)