本文整理汇总了Python中bluepy.btle.Peripheral.disconnect方法的典型用法代码示例。如果您正苦于以下问题:Python Peripheral.disconnect方法的具体用法?Python Peripheral.disconnect怎么用?Python Peripheral.disconnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bluepy.btle.Peripheral
的用法示例。
在下文中一共展示了Peripheral.disconnect方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RileyLink
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import disconnect [as 别名]
class RileyLink(PacketRadio):
def __init__(self):
self.peripheral = None
self.pa_level_index = PA_LEVELS.index(0x84)
self.data_handle = None
self.logger = getLogger()
self.address = None
if os.path.exists(RILEYLINK_MAC_FILE):
with open(RILEYLINK_MAC_FILE, "r") as stream:
self.address = stream.read()
self.service = None
self.response_handle = None
self.notify_event = Event()
self.initialized = False
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:
if self.peripheral is not None:
self.disconnect()
raise
def disconnect(self, ignore_errors=True):
try:
if self.peripheral is None:
self.logger.info("Already disconnected")
return
self.logger.info("Disconnecting..")
if self.response_handle is not None:
response_notify_handle = self.response_handle + 1
notify_setup = b"\x00\x00"
self.peripheral.writeCharacteristic(response_notify_handle, notify_setup)
except BTLEException:
if not ignore_errors:
raise
finally:
try:
if self.peripheral is not None:
self.peripheral.disconnect()
self.peripheral = None
except BTLEException:
if ignore_errors:
self.logger.exception("Ignoring btle exception during disconnect")
else:
raise
def get_info(self):
try:
self.connect()
bs = self.peripheral.getServiceByUUID(XGATT_BATTERYSERVICE_UUID)
bc = bs.getCharacteristics(XGATT_BATTERY_CHAR_UUID)[0]
bch = bc.getHandle()
battery_value = int(self.peripheral.readCharacteristic(bch)[0])
self.logger.debug("Battery level read: %d", battery_value)
version, v_major, v_minor = self._read_version()
return { "battery_level": battery_value, "mac_address": self.address,
"version_string": version, "version_major": v_major, "version_minor": v_minor }
except BTLEException as btlee:
raise PacketRadioError("Error communicating with RileyLink") from btlee
finally:
self.disconnect()
def _read_version(self):
version = None
try:
if os.path.exists(RILEYLINK_VERSION_FILE):
with open(RILEYLINK_VERSION_FILE, "r") as stream:
#.........这里部分代码省略.........
示例2: write
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import disconnect [as 别名]
def write(self, characteristic, data):
try:
dev = Peripheral(self, self.addrType)
services = sorted(dev.services, key=lambda s: s.hndStart)
print_status("Searching for characteristic {}".format(characteristic))
char = None
for service in services:
if char is not None:
break
for _, c in enumerate(service.getCharacteristics()):
if str(c.uuid) == characteristic:
char = c
break
if char:
if "WRITE" in char.propertiesToString():
print_success("Sending {} bytes...".format(len(data)))
wwrflag = False
if "NO RESPONSE" in char.propertiesToString():
wwrflag = True
try:
char.write(data, wwrflag)
print_success("Data sent")
except Exception as err:
print_error("Error: {}".format(err))
else:
print_error("Not writable")
dev.disconnect()
except Exception as err:
print_error(err)
try:
dev.disconnect()
except Exception:
pass
return None
示例3: enumerate_services
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import disconnect [as 别名]
def enumerate_services(self):
print_status("Starting enumerating {} ({} dBm) ...".format(self.addr, self.rssi))
try:
dev = Peripheral(self, self.addrType)
services = sorted(dev.services, key=lambda s: s.hndStart)
data = []
for service in services:
if service.hndStart == service.hndEnd:
continue
data.append([
"{:04x} -> {:04x}".format(service.hndStart, service.hndEnd),
self._get_svc_description(service),
"",
"",
])
for _, char in enumerate(service.getCharacteristics()):
desc = self._get_char_description(char)
props = char.propertiesToString()
hnd = char.getHandle()
value = self._get_char(char, props)
data.append([
"{:04x}".format(hnd), desc, props, value
])
dev.disconnect()
return data
except Exception as err:
print_error(err)
try:
dev.disconnect()
except Exception as err:
print_error(err)
return None
示例4: pow
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import disconnect [as 别名]
print "Info, reading values!"
ch = p.getCharacteristics(uuid=data_uuid)[0]
rawVals = ch.read()
rawVal = (ord(rawVals[1])<<8)+ord(rawVals[0])
#object temp and ambient temp are calculated as shown below
mantissa = rawVal & 0x0FFF;
exponent = (rawVal >> 12) & 0xFF;
magnitude = pow(2.0, exponent);
output = (mantissa * magnitude);
print "Lux: %4.2f lx" % (output / 100.0)
print "Info, turning sensor off!"
ch = p.getCharacteristics(uuid=config_uuid)[0]
ch.write(sensorOff, withResponse=True)
except:
print "Fatal, unexpected error!"
traceback.print_exc()
raise
finally:
print "Info, disconnecting!"
p.disconnect()
finally:
quit()
示例5: SBrickCommunications
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import disconnect [as 别名]
class SBrickCommunications(threading.Thread, IdleObject):
def __init__(self, sbrick_addr):
threading.Thread.__init__(self)
IdleObject.__init__(self)
self.lock = threading.RLock()
self.drivingLock = threading.RLock()
self.eventSend = threading.Event()
self.sBrickAddr = sbrick_addr
self.owner_password = None
self.brickChannels = [
SBrickChannelDrive(0, self.eventSend),
SBrickChannelDrive(1, self.eventSend),
SBrickChannelDrive(2, self.eventSend),
SBrickChannelDrive(3, self.eventSend),
]
self.SBrickPeripheral = None
self.stopFlag = False
self.characteristicRemote = None
self.need_authentication = False
self.authenticated = False
self.channel_config_ids = dict()
def set_channel_config_id(self, channel, config_id):
self.channel_config_ids[config_id] = channel
self.brickChannels[channel].set_config_id(config_id)
def terminate(self):
self.stopFlag = True
def is_driving(self):
locked = self.drivingLock.acquire(False)
if locked:
self.drivingLock.release()
return not locked
def connect_to_sbrick(self, owner_password):
self.owner_password = owner_password
self.start()
def run(self):
try:
monotime = 0.0
self.SBrickPeripheral = Peripheral()
self.SBrickPeripheral.connect(self.sBrickAddr)
service = self.SBrickPeripheral.getServiceByUUID('4dc591b0-857c-41de-b5f1-15abda665b0c')
characteristics = service.getCharacteristics('02b8cbcc-0e25-4bda-8790-a15f53e6010f')
for characteristic in characteristics:
if characteristic.uuid == '02b8cbcc-0e25-4bda-8790-a15f53e6010f':
self.characteristicRemote = characteristic
if self.characteristicRemote is None:
return
self.emit('sbrick_connected')
self.need_authentication = self.get_need_authentication()
self.authenticated = not self.need_authentication
if self.need_authentication:
if self.password_owner is not None:
self.authenticate_owner(self.password_owner)
while not self.stopFlag:
if self.authenticated:
if monotonic.monotonic() - monotime >= 0.05:
self.send_command()
monotime = monotonic.monotonic()
self.eventSend.wait(0.01)
for channel in self.brickChannels:
if channel.decrement_run_timer():
monotime = 0.0
self.drivingLock.release()
# print("stop run normal")
self.emit("sbrick_channel_stop", channel.channel)
if channel.decrement_brake_timer():
self.drivingLock.release()
# print("stop brake timer")
monotime = 0.0
self.emit("sbrick_channel_stop", channel.channel)
if self.authenticated:
self.stop_all()
self.send_command()
self.SBrickPeripheral.disconnect()
self.emit('sbrick_disconnected_ok')
except BTLEException as ex:
self.emit("sbrick_disconnected_error", ex.message)
def get_channel(self, channel):
if isinstance(channel, six.integer_types):
return self.brickChannels[channel]
if isinstance(channel, six.string_types):
return self.brickChannels[self.channel_config_ids[channel]]
return None
def drive(self, channel, pwm, reverse, time, brake_after_time=False):
with self.lock:
#.........这里部分代码省略.........
示例6: LightBlueBean
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import disconnect [as 别名]
class LightBlueBean(DefaultDelegate):
# https://github.com/PunchThrough/bean-documentation/blob/master/app_message_types.md
MSG_ID_SERIAL_DATA = 0x0000
MSG_ID_BT_SET_ADV = 0x0500
MSG_ID_BT_SET_CONN = 0x0502
MSG_ID_BT_SET_LOCAL_NAME = 0x0504
MSG_ID_BT_SET_PIN = 0x0506
MSG_ID_BT_SET_TX_PWR = 0x0508
MSG_ID_BT_GET_CONFIG = 0x0510
MSG_ID_BT_ADV_ONOFF = 0x0512
MSG_ID_BT_SET_SCRATCH = 0x0514
MSG_ID_BT_GET_SCRATCH = 0x0515
MSG_ID_BT_RESTART = 0x0520
MSG_ID_GATING = 0x0550
MSG_ID_BL_CMD = 0x1000
MSG_ID_BL_FW_BLOCK = 0x1001
MSG_ID_BL_STATUS = 0x1002
MSG_ID_CC_LED_WRITE = 0x2000
MSG_ID_CC_LED_WRITE_ALL = 0x2001
MSG_ID_CC_LED_READ_ALL = 0x2002
MSG_ID_CC_LED_DATA = 0x2082
MSG_ID_CC_ACCEL_READ = 0x2010
MSG_ID_CC_ACCEL_DATA = 0x2090
MSG_ID_CC_TEMP_READ = 0x2011
MSG_ID_CC_TEMP_DATA = 0x2091
MSG_ID_CC_BATT_READ = 0x2015
MSG_ID_CC_BATT_DATA = 0x2095
MSG_ID_AR_SET_POWER = 0x3000
MSG_ID_AR_GET_CONFIG = 0x3006
MSG_ID_DB_LOOPBACK = 0xFE00
MSG_ID_DB_COUNTER = 0xFE01
def __init__(self, mac):
self.conn = Peripheral(mac)
self.conn.setDelegate(self)
self.count = 0
self.buffin = [None]*10
self.got1 = False
print('connected')
self.service = self.conn.getServiceByUUID(_LBN_UUID(0x10))
self.serial = self.service.getCharacteristics(_LBN_UUID(0x11)) [0]
#print(self.serial.propertiesToString())
# Turn on notificiations
self.conn.writeCharacteristic(0x2f, '\x01\x00', False)
i = 0
while True:
#print(self.serial.read())
self.write("a" * 60)
#self.write("a" * 5)
#self.sendCmd(LightBlueBean.MSG_ID_CC_ACCEL_READ)
self.conn.waitForNotifications(1)
time.sleep(1)
self.conn.disconnect()
def write(self, data):
self.sendCmd(LightBlueBean.MSG_ID_SERIAL_DATA, data)
def sendCmd(self, cmd, data = ""):
# https://github.com/PunchThrough/bean-documentation/blob/master/serial_message_protocol.md
gst = struct.pack("!BxH", len(data)+2, cmd) + data
crc = struct.pack("<H", crc16(gst, 0xFFFF))
gst += crc
gt_qty = len(gst)/19
if len(gst) % 19 != 0:
gt_qty += 1
#amnt = len(gst) / gt_qty
optimal_packet_size = 19
for ch in xrange(0, gt_qty):
data = gst[:optimal_packet_size]
gst = gst[optimal_packet_size:]
gt = 0
if ch == 0:
gt = 0x80
gt |= self.count << 5
gt |= gt_qty - ch - 1
gt = struct.pack("B", gt) + data
#print("<", hexdump(gt))
self.serial.write(gt)
#time.sleep(0.1)
self.count = (self.count + 1) % 4
def writeRaw(self, data):
self.conn.writeCharacteristic(0x0b, data, False)
def handleNotification(self, cHandle, data):
#print(">", hexdump(data))
gt = struct.unpack("B", data[0]) [0]
#gt_cntr = gt & 0x60
#.........这里部分代码省略.........
示例7: main
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import disconnect [as 别名]
def main():
# uuid definition
targetDevice = ""
targetUUID = UUID("08590f7e-db05-467e-8757-72f6f66666d4")
# targetUUID = UUID(0x2a2b)
serviceUUID = UUID("e20a39f4-73f5-4bc4-a12f-17d1ad666661")
# scanning for Bluetooth LE device
# P.S. root permission is needed
print "scanning started..."
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(5)
print "\n\nscanning completed...\n found %d device(s)\n" % len(devices)
for dev in devices:
print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
for (adtype, desc, value) in dev.getScanData():
print " %s = %s" % (desc, value)
try:
p = Peripheral(dev.addr, "random")
ch = p.getCharacteristics(uuid=targetUUID)
if len(ch) > 0:
print "the desired target found. the address is", dev.addr
targetDevice = dev.addr
except:
# print "Unexpected error:", sys.exc_info()[0]
print "Unable to connect"
print " "
finally:
p.disconnect()
# scanning completed, now continue to connect to device
if targetDevice == "":
# the target is not found. end.
print "no target was found."
else:
# the target found, continue to subscribe.
print "\n\nthe target device is ", targetDevice
print "now try to subscribe..."
try:
# try to get the handle first
p = Peripheral(targetDevice, "random")
p.setDelegate(NotificationDelegate())
# svc = p.getServiceByUUID(serviceUUID)
ch = p.getCharacteristics(uuid=targetUUID)[0] # svc.getCharacteristics(targetUUID)[0]
handle = ch.getHandle()
print handle
ch.write(struct.pack('<bb', 0x01, 0x00))
# ch.write(bytes('aa', 'utf-8'))
# p.writeCharacteristic(handle, struct.pack('<bb', 0x01, 0x00), True)
print
# Main loop
while True:
if p.waitForNotifications(5):
# handleNotification() was called
continue
print "Waiting..."
# Perhaps do something else here
# except:
# print "Unexpected error:", sys.exc_info()[0]
finally:
p.disconnect()
示例8: OpenBCIGanglion
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import disconnect [as 别名]
class OpenBCIGanglion(object):
"""
Handle a connection to an OpenBCI board.
Args:
port: MAC address of the Ganglion Board. "None" to attempt auto-detect.
aux: enable on not aux channels (i.e. switch to 18bit mode if set)
impedance: measures impedance when start streaming
timeout: in seconds, if set will try to disconnect / reconnect after a period without new data
-- should be high if impedance check
max_packets_to_skip: will try to disconnect / reconnect after too many packets are skipped
baud, filter_data, daisy: Not used, for compatibility with v3
"""
def __init__(self, port=None, baud=0, filter_data=False,
scaled_output=True, daisy=False, log=True, aux=False, impedance=False, timeout=2,
max_packets_to_skip=20):
# unused, for compatibility with Cyton v3 API
self.daisy = False
# these one are used
self.log = log # print_incoming_text needs log
self.aux = aux
self.streaming = False
self.timeout = timeout
self.max_packets_to_skip = max_packets_to_skip
self.scaling_output = scaled_output
self.impedance = impedance
# might be handy to know API
self.board_type = "ganglion"
print("Looking for Ganglion board")
if port == None:
port = self.find_port()
self.port = port # find_port might not return string
self.connect()
self.streaming = False
# number of EEG channels and (optionally) accelerometer channel
self.eeg_channels_per_sample = 4
self.aux_channels_per_sample = 3
self.imp_channels_per_sample = 5
self.read_state = 0
self.log_packet_count = 0
self.packets_dropped = 0
self.time_last_packet = 0
# Disconnects from board when terminated
atexit.register(self.disconnect)
def getBoardType(self):
""" Returns the version of the board """
return self.board_type
def setImpedance(self, flag):
""" Enable/disable impedance measure """
self.impedance = bool(flag)
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:
#.........这里部分代码省略.........