Python bluepy.btle.Peripheral() Examples
The following are 30
code examples of bluepy.btle.Peripheral().
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 also want to check out all available functions/classes of the module
bluepy.btle
, or try the search function
.
Example #1
Source File: __init__.py From python-awox-mesh-light with MIT License | 13 votes |
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 #2
Source File: lib_miflora.py From rpieasy with GNU General Public License v3.0 | 8 votes |
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 #3
Source File: _C021_BLEDirect.py From rpieasy with GNU General Public License v3.0 | 8 votes |
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
Source File: bluepy.py From btlewrap with MIT License | 8 votes |
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 #5
Source File: sensor.py From Xiaomi_Hygrothermo with MIT License | 7 votes |
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 #6
Source File: read_waveplus.py From waveplus-reader with MIT License | 7 votes |
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 #7
Source File: connection.py From python-eq3bt with MIT License | 7 votes |
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 #8
Source File: client.py From lywsd02 with MIT License | 7 votes |
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 #9
Source File: cve-2017-8403.py From HomePWN with GNU General Public License v3.0 | 7 votes |
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 #10
Source File: lywsd03mmc.py From bt-mqtt-gateway with MIT License | 6 votes |
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 #11
Source File: _P512_BLEMijia.py From rpieasy with GNU General Public License v3.0 | 6 votes |
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 #12
Source File: __init__.py From python-tikteck with MIT License | 6 votes |
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 #13
Source File: unlock-bozzys.py From snippets with MIT License | 6 votes |
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 #14
Source File: read_wave2.py From wave-reader with MIT License | 5 votes |
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 #15
Source File: commBLE.py From blue-loader-python with Apache License 2.0 | 5 votes |
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 #16
Source File: Calima.py From pycalima with Apache License 2.0 | 5 votes |
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 #17
Source File: open_myo.py From Open-Myo with GNU General Public License v3.0 | 5 votes |
def __init__(self, mac): btle.Peripheral.__init__(self, mac) time.sleep(0.5) # Get the firmware version
Example #18
Source File: pr_rileylink.py From omnipy with MIT License | 5 votes |
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 #19
Source File: ganglion.py From pyOpenBCI with MIT License | 5 votes |
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 #20
Source File: ble_tools.py From peniot with MIT License | 5 votes |
def __init__(self, address, address_type, interface): self.device = btle.Peripheral(address, address_type, interface)
Example #21
Source File: unlock-nokelock.py From snippets with MIT License | 5 votes |
def setAddr(self,addr): self.addr=addr self.p = Peripheral(self.addr, addrType=ADDR_TYPE_PUBLIC) self.p.setDelegate(NotifyDelegate())
Example #22
Source File: cbluepy.py From pylgbst with MIT License | 5 votes |
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 #23
Source File: mikettle.py From mikettle with MIT License | 5 votes |
def connect(self): self._p = Peripheral(deviceAddr=self._mac, iface=self._iface) self._p.setDelegate(self)
Example #24
Source File: ble.py From HomePWN with GNU General Public License v3.0 | 5 votes |
def connect(self): self.device = Peripheral(self.bmac, self.type, self.iface) print_ok("connected")
Example #25
Source File: gatt.py From csrmesh with GNU Lesser General Public License v3.0 | 5 votes |
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 #26
Source File: gatt.py From csrmesh with GNU Lesser General Public License v3.0 | 5 votes |
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 #27
Source File: ibbq.py From bt-mqtt-gateway with MIT License | 5 votes |
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 #28
Source File: lywsd02.py From bt-mqtt-gateway with MIT License | 5 votes |
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 #29
Source File: read_wave.py From wave-reader with MIT License | 5 votes |
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 #30
Source File: _P510_ITag.py From rpieasy with GNU General Public License v3.0 | 4 votes |
def connectproc(self): try: if self.blestatus.isscaninprogress(): self.blestatus.requeststopscan(self.taskindex) return False except Exception as e: return False self.blestatus.registerdataprogress(self.taskindex) prevstate = self.connected self.conninprogress = True try: misc.addLog(rpieGlobals.LOG_LEVEL_INFO,"BLE connection initiated to "+str(self.taskdevicepluginconfig[0])) self.BLEPeripheral = btle.Peripheral(str(self.taskdevicepluginconfig[0]),iface=self.taskdevicepluginconfig[3]) self.connected = True self.afterconnection() except: self.setdisconnectstate() # disconnected! self.conninprogress = False self.isconnected() publishchange = (self.connected != prevstate) if self.connected: # self.set_value(2,self.connected,publishchange) self.handlevalue(-1,self.connected) else: self.handlevalue(0,0) # self.set_value(1,0,False) # self.set_value(2,0,False,suserssi=-100,susebattery=0) if publishchange: self.plugin_senddata() misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"BLE connection failed "+str(self.taskdevicepluginconfig[0])) return False if self.connected and self.handshake: misc.addLog(rpieGlobals.LOG_LEVEL_INFO,"BLE connected to "+str(self.taskdevicepluginconfig[0])) self.waitnotifications = True while self.waitnotifications: try: self.BLEPeripheral.waitForNotifications(0.5) except Exception as e: self.waitnotifications = False self.setdisconnectstate() # disconnected! self.setdisconnectstate(False) # disconnected!