Python bluepy.btle.Peripheral() Examples

The following are 30 code examples for showing how to use bluepy.btle.Peripheral(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module bluepy.btle , or try the search function .

Example 1
Project: pylgbst   Author: undera   File: cbluepy.py    License: MIT License 6 votes vote down vote up
def _dispatch_calls(self):
        self._peripheral = btle.Peripheral(self._addr, self._addrType, self._iface_number)
        try:
            while not self._disconnect_event.is_set():
                try:
                    try:
                        method = self._call_queue.get(False)
                        method()
                    except queue.Empty:
                        pass
                    self._peripheral.waitForNotifications(1.)
                except Exception as ex:
                    log.exception('Exception in call dispatcher thread', exc_info=ex)
                    if PROPAGATE_DISPATCHER_EXCEPTION:
                        log.error("Terminating dispatcher thread.")
                        raise
        finally:
            self._peripheral.disconnect() 
Example 2
Project: python-awox-mesh-light   Author: Leiaz   File: __init__.py    License: MIT License 6 votes vote down vote up
def __init__ (self, mac, mesh_name = "unpaired", mesh_password = "1234"):
        """
        Args :
            mac: The light's MAC address as a string in the form AA:BB:CC:DD:EE:FF
            mesh_name: The mesh name as a string.
            mesh_password: The mesh password as a string.
        """
        self.mac = mac
        self.mesh_id = 0
        self.btdevice = btle.Peripheral ()
        self.session_key = None
        self.mesh_name = mesh_name.encode ()
        self.mesh_password = mesh_password.encode ()
        
        # Light status
        self.white_brightness = None
        self.white_temp = None
        self.red = None
        self.green = None
        self.blue = None 
Example 3
Project: rpieasy   Author: enesbcs   File: _C021_BLEDirect.py    License: GNU General Public License v3.0 6 votes vote down vote up
def connect(self):
       if self.tx_active or self.address=="":
        return False
       self.tx_start = millis()
       if self.tx_start<self.nexttransmit:
        print("Next possible transmit ",self.nexttransmit)
        return False
       self.tx_active = True
       try:
        self.periph = Peripheral(self.address)
       except Exception as e: 
#        print("connect error",e)
        self.tx_active = False
        self.tx_end = millis()
        return False
       try:
        self.service = self.periph.getServiceByUUID(BLE_SERVICE_ID)
       except Exception as e:
#        print("service error ",e)
        self.tx_active = False
        self.tx_end = millis()
        return False
       return True 
Example 4
Project: rpieasy   Author: enesbcs   File: lib_miflora.py    License: GNU General Public License v3.0 6 votes vote down vote up
def firmware_version(self):
        if (self.battery==255) or (self._firmware_version=="") or (datetime.now() - timedelta(hours=1) > self._fw_last_read) and (self.busy==False): # 1 hour timeout fixed
          self._fw_last_read = datetime.now()
          try:
            self.busy = True
            peripheral = btle.Peripheral(self.address,iface=self.interface)
            received_bytes = bytearray(peripheral.readCharacteristic(_HANDLE_READ_VERSION_BATTERY))
            self.battery = received_bytes[0]
            self._firmware_version = "".join(map(chr, received_bytes[2:]))
            peripheral.disconnect()
            self.busy = False
          except:
            self.busy = False
            self.battery = 255
            self._firmware_version = ""
        return self._firmware_version 
Example 5
Project: python-eq3bt   Author: rytilahti   File: connection.py    License: MIT License 6 votes vote down vote up
def __enter__(self):
        """
        Context manager __enter__ for connecting the device
        :rtype: btle.Peripheral
        :return:
        """
        self._conn = btle.Peripheral()
        self._conn.withDelegate(self)
        _LOGGER.debug("Trying to connect to %s", self._mac)
        try:
            self._conn.connect(self._mac)
        except btle.BTLEException as ex:
            _LOGGER.debug("Unable to connect to the device %s, retrying: %s", self._mac, ex)
            try:
                self._conn.connect(self._mac)
            except Exception as ex2:
                _LOGGER.debug("Second connection try to %s failed: %s", self._mac, ex2)
                raise

        _LOGGER.debug("Connected to %s", self._mac)
        return self 
Example 6
Project: btlewrap   Author: ChristianKuehnel   File: bluepy.py    License: MIT License 5 votes vote down vote up
def connect(self, mac: str):
        """Connect to a device."""
        from bluepy.btle import Peripheral
        match_result = re.search(r'hci([\d]+)', self.adapter)
        if match_result is None:
            raise BluetoothBackendException(
                'Invalid pattern "{}" for BLuetooth adpater. '
                'Expetected something like "hci0".'.format(self.adapter))
        iface = int(match_result.group(1))
        self._peripheral = Peripheral(mac, iface=iface, addrType=self.address_type) 
Example 7
Project: Xiaomi_Hygrothermo   Author: dolezsa   File: sensor.py    License: MIT License 5 votes vote down vote up
def get_data(self, now = None):
        try:
            from bluepy import btle

            p = btle.Peripheral(self.address)

            #self.name = ''.join(map(chr, p.readCharacteristic(0x3)))
            #self.firmware = ''.join(map(chr, p.readCharacteristic(0x24)))
            if self.last_battery is None or (utcnow() - self.last_battery).seconds >= 3600:
                self.battery = p.readCharacteristic(0x18)[0]
                self.last_battery = utcnow()

            delegate = XiomiHygroThermoDelegate()
            p.withDelegate( delegate )
            p.writeCharacteristic(0x10, bytearray([1, 0]), True)
            while not delegate.received:
                p.waitForNotifications(30.0)

            self.temperature = delegate.temperature
            self.humidity = delegate.humidity

            ok = True
        except Exception as ex:
            if isinstance(ex, btle.BTLEException):
                _LOGGER.warning("BT connection error: {}".format(ex))
            else:
                _LOGGER.error("Unexpected error: {}".format(ex))
            ok = False

        for i in [0, 1]:
            changed = self.entities[i].set_state(ok, self.battery, self.temperature if i == 0 else self.humidity)
            if (not now is None) and changed:
                self.entities[i].async_schedule_update_ha_state() 
Example 8
Project: waveplus-reader   Author: Airthings   File: read_waveplus.py    License: MIT License 5 votes vote down vote up
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] 
Example 9
Project: snippets   Author: pentestpartners   File: unlock-bozzys.py    License: MIT License 5 votes vote down vote up
def connect(self):
        self.p = Peripheral(self.addr, addrType=ADDR_TYPE_PUBLIC)
        self.p.setDelegate(NotifyDelegate())
        # Start listening for notification
        self.p.writeCharacteristic(0x39,b'\x01\x00') 
Example 10
Project: snippets   Author: pentestpartners   File: unlock-nokelock.py    License: MIT License 5 votes vote down vote up
def setAddr(self,addr):
        self.addr=addr
        self.p = Peripheral(self.addr, addrType=ADDR_TYPE_PUBLIC)
        self.p.setDelegate(NotifyDelegate()) 
Example 11
Project: lywsd02   Author: h4   File: client.py    License: MIT License 5 votes vote down vote up
def __init__(self, mac, notification_timeout=5.0):
        self._mac = mac
        self._peripheral = btle.Peripheral()
        self._notification_timeout = notification_timeout
        self._handles = {}
        self._tz_offset = None
        self._data = SensorData(None, None)
        self._history_data = collections.OrderedDict()
        self._context_depth = 0 
Example 12
Project: mikettle   Author: drndos   File: mikettle.py    License: MIT License 5 votes vote down vote up
def connect(self):
        self._p = Peripheral(deviceAddr=self._mac, iface=self._iface)
        self._p.setDelegate(self) 
Example 13
Project: csrmesh   Author: nkaminski   File: gatt.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect(mac_list, debug=False):
    #Try to connect to each device in mac_list in order, returning after the first successful connection, or returning None after all attempts fail.
    device=None
    for mac in mac_list:
        try:
            if debug:
                print("[+] Connecting to device %s" % mac)
            device = btle.Peripheral(mac, addrType=btle.ADDR_TYPE_PUBLIC)
            return device
        except btle.BTLEException as err:
            if debug:
                print("[-] A connection error has occured: %s" % str(err))
    return None 
Example 14
Project: csrmesh   Author: nkaminski   File: gatt.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def send_packet(dest, handle, p, debug=False):
    #Send the packet, dest may either be one or more MAC addresses represented as a comma separated string, or a btle.Peripheral object connected to the target
    #First 20 bytes to handle, if more than 20 bytes send the next bytes to handle+3

    #Make a connection if we were given an address, otherwise reuse the handle we were given
    if isinstance(dest, btle.Peripheral):
        if debug:
            print("[+] Reusing connection handle")
        device=dest
    else:
        device=connect(dest.split(','), debug)
        if not device:
            if debug:
                print("[-] Connection to mesh failed")
            return False

    #Write to the device
    try:
        gatt_write(device, handle, p[0:20], debug)
        if len(p) > 20:
            gatt_write(device, handle+3, p[20:], debug)

    except btle.BTLEException as err:
        if debug:
            print("[-] A communication error has occured: %s" % str(err))
        return False

    finally:
        #Disconnect from the device, but only if we made the connection
        if not isinstance(dest, btle.Peripheral):
            disconnect(device, debug)
        if debug:
            print("[+] Communication complete")

    return True 
Example 15
Project: wave-reader   Author: Airthings   File: read_wave.py    License: MIT License 5 votes vote down vote up
def connect(self, retries=1):
        tries = 0
        while (tries < retries and self.is_connected() is False):
            tries += 1
            if self.mac_addr is None:
                self.mac_addr = self.discover()
            try:
                self._periph = btle.Peripheral(self.mac_addr)
                self._datetime_char = self._periph.getCharacteristics(uuid=self.DATETIME_UUID)[0]
                self._humidity_char = self._periph.getCharacteristics(uuid=self.HUMIDITY_UUID)[0]
                self._temperature_char = self._periph.getCharacteristics(uuid=self.TEMPERATURE_UUID)[0]
                self._radon_sta_char = self._periph.getCharacteristics(uuid=self.RADON_STA_UUID)[0]
                self._radon_lta_char = self._periph.getCharacteristics(uuid=self.RADON_LTA_UUID)[0]
            except Exception:
                if tries == retries:
                    raise
                else:
                    pass 
Example 16
Project: wave-reader   Author: Airthings   File: read_wave2.py    License: MIT License 5 votes vote down vote up
def connect(self, retries=1):
        tries = 0
        while (tries < retries and self.is_connected() is False):
            tries += 1
            if self.mac_addr is None:
                self.mac_addr = self.discover()
            try:
                self._periph = btle.Peripheral(self.mac_addr)
                self._char = self._periph.getCharacteristics(uuid=self.CURR_VAL_UUID)[0]
            except Exception:
                if tries == retries:
                    raise
                else:
                    pass 
Example 17
Project: bt-mqtt-gateway   Author: zewelor   File: lywsd02.py    License: MIT License 5 votes vote down vote up
def connected(self):
        from bluepy import btle

        _LOGGER.debug("%s connected ", self.mac)
        device = btle.Peripheral()
        device.connect(self.mac)
        yield device
        device.disconnect() 
Example 18
Project: bt-mqtt-gateway   Author: zewelor   File: ibbq.py    License: MIT License 5 votes vote down vote up
def connect(self, timeout=5):
        from bluepy import btle

        try:
            device = btle.Peripheral(self.mac)
            _LOGGER.debug("%s connected ", self.mac)
            return device
        except btle.BTLEDisconnectError as er:
            _LOGGER.debug("failed connect %s", er) 
Example 19
Project: bt-mqtt-gateway   Author: zewelor   File: lywsd03mmc.py    License: MIT License 5 votes vote down vote up
def connected(self):
        from bluepy import btle

        _LOGGER.debug("%s connected ", self.mac)
        device = btle.Peripheral()
        device.connect(self.mac)
        device.writeCharacteristic(0x0038, b'\x01\x00', True)
        device.writeCharacteristic(0x0046, b'\xf4\x01\x00', True)
        yield device 
Example 20
Project: HomePWN   Author: ElevenPaths   File: cve-2017-8403.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        uuid = "36d25039-5cbc-5ee5-b688-b90fda300d6"
        bmac = self.args["bmac"]
        try:
            iface = int(self.args["iface"])
        except:
            iface = 0
        print_info(f"Trying to connect {bmac}")
        try:
            p = Peripheral(bmac, "random", iface)
            print_ok("connected")
        except KeyboardInterrupt:
            print_info("Interrupted... exit run")
            return 
        except:
            print_error("Failed to connect")
            return
        try:
            ch = p.getCharacteristics(uuid=uuid)[0]
            if "WRITE" in ch.propertiesToString():
                print_ok("Good! It's writable!")
            else:
                print_error("It is not writable")
                return

            hex_password =  bytes.fromhex(self.args['password'].replace("0x",""))
            print_info(f"Updating Password in {bmac}")
            ch.write(hex_password)
            print_ok("Done!")
        except:
            print_error("It was not possible to write") 
Example 21
Project: HomePWN   Author: ElevenPaths   File: ble.py    License: GNU General Public License v3.0 5 votes vote down vote up
def connect(self):
       self.device = Peripheral(self.bmac, self.type, self.iface)
       print_ok("connected") 
Example 22
Project: python-tikteck   Author: mjg59   File: __init__.py    License: MIT License 5 votes vote down vote up
def connect(self):
    self.device = btle.Peripheral(self.mac, addrType=btle.ADDR_TYPE_PUBLIC)
    data = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0, 0, 0, 0, 0, 0, 0, 0]
    enc_data = key_encrypt(self.name, self.password, data)
    packet = [0x0c]
    packet += data[0:8]
    packet += enc_data[0:8]
    try:
      self.device.writeCharacteristic(0x1b, bytes(packet), withResponse=True)
      time.sleep(0.3)
      data2 = self.device.readCharacteristic(0x1b)
    except:
      return False
    self.sk = generate_sk(self.name, self.password, data[0:8], data2[1:9]) 
Example 23
Project: rpieasy   Author: enesbcs   File: _P512_BLEMijia.py    License: GNU General Public License v3.0 5 votes vote down vote up
def connectproc(self):
   try:
    if self.blestatus.isscaninprogress():
     self.blestatus.requeststopscan(self.taskindex)
     return False
   except Exception as e:
    return False
   self.conninprogress = True
   self.blestatus.registerdataprogress(self.taskindex)
   prevstate = self.connected
   try:
    misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,"BLE connection initiated to "+str(self.taskdevicepluginconfig[0]))
    time.sleep(uniform(0.4,1.8))
    self.BLEPeripheral = btle.Peripheral(str(self.taskdevicepluginconfig[0]),iface=self.taskdevicepluginconfig[2])
    self.connected = True
    self.failures = 0
    self.BLEPeripheral.setDelegate( TempHumDelegate(self.callbackfunc) )
   except:
    self.connected = False
   self.conninprogress = False
   self.isconnected()
   if self.connected==False:
    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"BLE connection failed "+str(self.taskdevicepluginconfig[0]))
    self.blestatus.unregisterdataprogress(self.taskindex)
    self.failures =  self.failures +1
    if self.failures>5:
     self._nextdataservetime = rpieTime.millis()+(self.interval*5000)
     self._lastdataservetime = self._nextdataservetime
    return False
   else:
    misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,"BLE connected to "+str(self.taskdevicepluginconfig[0]))
    self.waitnotifications = True
    self.get_battery_value()
    rpieTime.addsystemtimer(3,self.isconnected,[-1]) 
Example 24
Project: peniot   Author: yakuza8   File: ble_tools.py    License: MIT License 5 votes vote down vote up
def __init__(self, address, address_type, interface):
        self.device = btle.Peripheral(address, address_type, interface) 
Example 25
Project: pyOpenBCI   Author: openbci-archive   File: ganglion.py    License: MIT License 5 votes vote down vote up
def connect(self):
        """Establishes connection with the specified Ganglion board."""
        self.ganglion = Peripheral(self.mac_address, 'random')

        self.service = self.ganglion.getServiceByUUID(BLE_SERVICE)

        self.char_read = self.service.getCharacteristics(BLE_CHAR_RECEIVE)[0]

        self.char_write = self.service.getCharacteristics(BLE_CHAR_SEND)[0]

        self.char_discon = \
            self.service.getCharacteristics(BLE_CHAR_DISCONNECT)[0]

        self.ble_delegate = GanglionDelegate(self.max_packets_skipped)
        self.ganglion.setDelegate(self.ble_delegate)

        self.desc_notify = self.char_read.getDescriptors(forUUID=0x2902)[0]

        try:
            self.desc_notify.write(b"\x01")
        except Exception as e:
            self._logger.error(
                "Something went wrong while trying to enable notifications:", e)
            sys.exit(2)

        self._logger.debug("Connection established.") 
Example 26
Project: omnipy   Author: winemug   File: pr_rileylink.py    License: MIT License 5 votes vote down vote up
def connect(self, force_initialize=False):
        try:
            if self.address is None:
                self.address = self._findRileyLink()

            if self.peripheral is None:
                self.peripheral = Peripheral()

            try:
                state = self.peripheral.getState()
                if state == "conn":
                    return
            except BTLEException:
                pass

            self._connect_retry(3)

            self.service = self.peripheral.getServiceByUUID(RILEYLINK_SERVICE_UUID)
            data_char = self.service.getCharacteristics(RILEYLINK_DATA_CHAR_UUID)[0]
            self.data_handle = data_char.getHandle()

            char_response = self.service.getCharacteristics(RILEYLINK_RESPONSE_CHAR_UUID)[0]
            self.response_handle = char_response.getHandle()

            response_notify_handle = self.response_handle + 1
            notify_setup = b"\x01\x00"
            self.peripheral.writeCharacteristic(response_notify_handle, notify_setup)

            while self.peripheral.waitForNotifications(0.05):
                self.peripheral.readCharacteristic(self.data_handle)

            if self.initialized:
                self.init_radio(force_initialize)
            else:
                self.init_radio(True)
        except BTLEException as be:
            if self.peripheral is not None:
                self.disconnect()
            raise PacketRadioError("Error while connecting") from be
        except Exception as e:
            raise PacketRadioError("Error while connecting") from e 
Example 27
Project: Open-Myo   Author: Alvipe   File: open_myo.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, mac):
        btle.Peripheral.__init__(self, mac)
        time.sleep(0.5)

    # Get the firmware version 
Example 28
Project: pycalima   Author: PatrickE94   File: Calima.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, addr, pin):
        # Set debug to true if you want more verbose output
        self._debug = False
        self.conn = ble.Peripheral(deviceAddr=addr)
        self.setAuth(pin) 
Example 29
Project: blue-loader-python   Author: LedgerHQ   File: commBLE.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, bleAddress, configDescriptor, debug=False):
		self.device = btle.Peripheral(bleAddress)		
		self.device.setDelegate(BLEDongleDelegate(self))
		self.service = self.device.getServiceByUUID(SERVICE_UUID)
		self.writeCharacteristic = self.service.getCharacteristics(forUUID=WRITE_CHARACTERISTICS_UUID)[0]
		self.device.writeCharacteristic(configDescriptor, ENABLE_NOTIFICATION, withResponse=True)
		self.debug = debug
		self.opened = True 
Example 30
Project: OpenBCI_Python   Author: openbci-archive   File: ganglion.py    License: MIT License 4 votes vote down vote up
def connect(self):
        """ Connect to the board and configure it. Note: recreates various objects upon call. """
        print("Init BLE connection with MAC: " + self.port)
        print("NB: if it fails, try with root privileges.")
        self.gang = Peripheral(self.port, 'random')  # ADDR_TYPE_RANDOM

        print("Get mainservice...")
        self.service = self.gang.getServiceByUUID(BLE_SERVICE)
        print("Got:" + str(self.service))

        print("Get characteristics...")
        self.char_read = self.service.getCharacteristics(BLE_CHAR_RECEIVE)[0]
        print("receive, properties: " + str(self.char_read.propertiesToString()) +
              ", supports read: " + str(self.char_read.supportsRead()))

        self.char_write = self.service.getCharacteristics(BLE_CHAR_SEND)[0]
        print("write, properties: " + str(self.char_write.propertiesToString()) +
              ", supports read: " + str(self.char_write.supportsRead()))

        self.char_discon = self.service.getCharacteristics(BLE_CHAR_DISCONNECT)[0]
        print("disconnect, properties: " + str(self.char_discon.propertiesToString()) +
              ", supports read: " + str(self.char_discon.supportsRead()))

        # set delegate to handle incoming data
        self.delegate = GanglionDelegate(self.scaling_output)
        self.gang.setDelegate(self.delegate)

        # enable AUX channel
        if self.aux:
            print("Enabling AUX data...")
            try:
                self.ser_write(b'n')
            except Exception as e:
                print("Something went wrong while enabling aux channels: " + str(e))

        print("Turn on notifications")
        # nead up-to-date bluepy, cf https://github.com/IanHarvey/bluepy/issues/53
        self.desc_notify = self.char_read.getDescriptors(forUUID=0x2902)[0]
        try:
            self.desc_notify.write(b"\x01")
        except Exception as e:
            print("Something went wrong while trying to enable notification: " + str(e))

        print("Connection established")