本文整理汇总了Python中bluepy.btle.Peripheral.getServiceByUUID方法的典型用法代码示例。如果您正苦于以下问题:Python Peripheral.getServiceByUUID方法的具体用法?Python Peripheral.getServiceByUUID怎么用?Python Peripheral.getServiceByUUID使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bluepy.btle.Peripheral
的用法示例。
在下文中一共展示了Peripheral.getServiceByUUID方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RileyLink
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [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: Nuimo
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [as 别名]
class Nuimo(object):
SERVICE_UUIDS = [
UUID('0000180f-0000-1000-8000-00805f9b34fb'), # Battery
UUID('f29b1525-cb19-40f3-be5c-7241ecb82fd2'), # Sensors
UUID('f29b1523-cb19-40f3-be5c-7241ecb82fd1') # LED Matrix
]
CHARACTERISTIC_UUIDS = {
UUID('00002a19-0000-1000-8000-00805f9b34fb'): 'BATTERY',
UUID('f29b1529-cb19-40f3-be5c-7241ecb82fd2'): 'BUTTON',
UUID('f29b1528-cb19-40f3-be5c-7241ecb82fd2'): 'ROTATION',
UUID('f29b1527-cb19-40f3-be5c-7241ecb82fd2'): 'SWIPE',
UUID('f29b1526-cb19-40f3-be5c-7241ecb82fd2'): 'FLY',
UUID('f29b1524-cb19-40f3-be5c-7241ecb82fd1'): 'LED_MATRIX'
}
NOTIFICATION_CHARACTERISTIC_UUIDS = [
'BATTERY', # Uncomment only if you are not using the iOS emulator (iOS does't support battery updates without authentication)
'BUTTON',
'ROTATION',
'SWIPE',
'FLY']
# Notification data
NOTIFICATION_ON = struct.pack("BB", 0x01, 0x00)
NOTIFICATION_OFF = struct.pack("BB", 0x00, 0x00)
def __init__(self, mac_address):
self.macAddress = mac_address
self.delegate=NuimoDelegate(self)
def set_delegate(self, delegate):
self.delegate = delegate
def connect(self):
self.peripheral = Peripheral(self.macAddress, addrType='random')
# Retrieve all characteristics from desired services and map them from their UUID
characteristics = list(itertools.chain(*[self.peripheral.getServiceByUUID(uuid).getCharacteristics() for uuid in Nuimo.SERVICE_UUIDS]))
characteristics = dict((c.uuid, c) for c in characteristics)
# Store each characteristic's value handle for each characteristic name
self.characteristicValueHandles = dict((name, characteristics[uuid].getHandle()) for uuid, name in Nuimo.CHARACTERISTIC_UUIDS.items())
# Subscribe for notifications
for name in Nuimo.NOTIFICATION_CHARACTERISTIC_UUIDS:
self.peripheral.writeCharacteristic(self.characteristicValueHandles[name] + 1, Nuimo.NOTIFICATION_ON, True)
self.peripheral.setDelegate(self.delegate)
def wait_for_notifications(self):
self.peripheral.wait_for_notifications(1.0)
def display_led_matrix(self, matrix, timeout, brightness=1.0):
matrix = '{:<81}'.format(matrix[:81])
bites = list(map(lambda leds: reduce(lambda acc, led: acc + (1 << led if leds[led] not in [' ', '0'] else 0), range(0, len(leds)), 0), [matrix[i:i+8] for i in range(0, len(matrix), 8)]))
self.peripheral.writeCharacteristic(self.characteristicValueHandles['LED_MATRIX'], struct.pack('BBBBBBBBBBBBB', bites[0], bites[1], bites[2], bites[3], bites[4], bites[5], bites[6], bites[7], bites[8], bites[9], bites[10], max(0, min(255, int(255.0 * brightness))), max(0, min(255, int(timeout * 10.0)))), True)
示例3: NotifyDelegate
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [as 别名]
class YeelightService:
"""
YeelightService is the yeelight control util for python
author zhaohui.sol
"""
SERVICE = "0000FFF0-0000-1000-8000-00805F9B34FB"
CHAR_CONTROL = "0000FFF1-0000-1000-8000-00805F9B34FB"
CHAR_DELAY = "0000FFF2-0000-1000-8000-00805F9B34FB"
CHAR_DELAY_QUERY = "0000FFF3-0000-1000-8000-00805F9B34FB"
CHAR_DELAY_NOTIFY = "0000FFF4-0000-1000-8000-00805F9B34FB"
CHAR_QUERY = "0000FFF5-0000-1000-8000-00805F9B34FB"
CHAR_NOTIFY = "0000FFF6-0000-1000-8000-00805F9B34FB"
CHAR_COLOR_FLOW = "0000FFF7-0000-1000-8000-00805F9B34FB"
CHAR_NAME = "0000FFF8-0000-1000-8000-00805F9B34FB"
CHAR_NAME_NOTIFY = "0000FFF9-0000-1000-8000-00805F9B34FB"
CHAR_COLOR_EFFECT = "0000FFFC-0000-1000-8000-00805F9B34FB"
class NotifyDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
self.queue = list()
def register(self,callback):
self.queue.append(callback)
def deregister(self,callback):
self.queue.remove(callback)
def handleNotification(self,handle,data):
logging.warning("notify data %s from %s." % (data,handle))
res = dict()
res['data'] = data
res['handle'] = handle
for c in self.queue:
c(res)
def __init__(self,address):
"""
address is the yeelight blue ble hardware address
"""
self.data = dict()
self.address = address
self.delegate = YeelightService.NotifyDelegate()
self.peripher = Peripheral(deviceAddr = address)
self.service = self.peripher.getServiceByUUID(YeelightService.SERVICE)
self.peripher.withDelegate(self.delegate)
def __character_by_uuid__(self,uuid):
'''
get character by a special uuid
'''
characters = self.service.getCharacteristics(forUUID=uuid)
return characters[0] if characters else None
def __write_character__(self,uuid,strdata):
'''
write data to a special uuid
'''
logging.info(u"write %s to %s." % (strdata,uuid))
character = self.__character_by_uuid__(uuid)
if character:
character.write(strdata)
else:
pass
def __read_character__(self,uuid):
'''
read data from a special uuid,may be it's wrong
'''
logging.info(u"read data from %s." % uuid)
character = self.__character_by_uuid__(uuid)
if character:
return character.read()
else:
return None
def __notify_character__(self,_to,_write):
'''
write data to the uuid and wait data notify
'''
res = dict()
def callback(data):
for k in data:
res[k] = data[k]
self.delegate.register(callback)
self.__write_character__(_to,_write)
#.........这里部分代码省略.........
示例4: SBrickCommunications
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [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:
#.........这里部分代码省略.........
示例5: LightBlueBean
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [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
#.........这里部分代码省略.........
示例6: OpenBCIGanglion
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [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:
#.........这里部分代码省略.........
示例7: UUID
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [as 别名]
washer_service_uuid = UUID("6e400001-b5a3-f393-e0a9-e50e24dcca9e")
battery_service_uuid = UUID("180F")
#washer service Characteristics의 센서에서 전송하는 정보이며 Access Permisson은 Notify
washerTX_char_uuid = UUID("6e400003-b5a3-f393-e0a9-e50e24dcca9e")
battery_level_uuid = UUID("00002a19-0000-1000-8000-00805f9b34fb")
#if len(sys.argv) != 2:
# print ("Fatal, must pass device address:", sys.argv[0], "<device address="">")
# quit()
p = Peripheral("c7:74:31:9A:F8:D1","random")
p.setDelegate( MyDelegate(p) )
#WasherService, BatteryService를 가져온다.
WasherService=p.getServiceByUUID(washer_service_uuid)
BatteryService =p.getServiceByUUID(battery_service_uuid)
#TX의 Characteristics를 가져온다.
WasherTX_C = WasherService.getCharacteristics(washerTX_char_uuid)[0]
#battey의 Characteristics를 가져온다.
Battery_C = BatteryService.getCharacteristics(battery_level_uuid)[0]
# Client Characteristic Descriptor의 handler
# 0x13 은 washerTX, 0x0F는 battery
# notifications의 비트를 1로 바꿔 활성화한다.
# 메인 루프 -----------------------
示例8: BleCam
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [as 别名]
class BleCam(object):
locked = True
def __init__(self, address, pincode):
print("Connecting to %s..." % address)
self.pincode = pincode
self.periph = Peripheral(address)
self._ipcamservice()
self.name = self.periph.getCharacteristics(uuid=0x2a00)[0].read().decode() # wellknown name characteristic
print("Connected to '%s'" % self.name)
def _ipcamservice(self):
try:
print("Verifying IPCam service")
self.service = self.periph.getServiceByUUID(0xd001)
self.handles = self.service.getCharacteristics()
except BTLEEException:
print("no IPCam service found for %s" % periph.address)
def dumpchars(self):
print("%s supports these characteristics:" % self.name)
for h in self.handles:
print("%s - Handle=%#06x (%s)" % (h.uuid, h.getHandle(), h.propertiesToString()))
def unlock(self):
if not self.locked:
return True
auth = self.service.getCharacteristics(0xa001)[0]
state = kv2dict(auth.read().decode())
# already unlocked?
if state["M"] == 0:
self.locked = False
return True
self.challenge = state["C"]
hashit = self.name + self.pincode + self.challenge
self.key = base64.b64encode(hashlib.md5(hashit.encode()).digest())[:16]
try:
auth.write("M=0;K=".encode() + self.key, True)
self.locked = False
except:
print("ERROR: failed to unlock %s - wrong pincode?" % self.name)
return not self.locked
def get_ipconfig(self):
if not self.unlock(): return
return kv2dict(self.service.getCharacteristics(0xa104)[0].read().decode())
def get_wificonfig(self):
if not self.unlock(): return
return kv2dict(self.service.getCharacteristics(0xa101)[0].read().decode())
def wifilink(self):
if not self.unlock(): return
r = kv2dict(self.service.getCharacteristics(0xa103)[0].read().decode())
return r["S"] == "1"
def sysinfo(self):
if not self.unlock(): return
return kv2dict(self.service.getCharacteristics(0xa200)[0].read().decode())
def setup_wifi(self, essid, passwd):
for net in self.wifi_scan():
if net["I"] == essid:
cfg = "M=" + net["M"] + ";I=" + essid + ";S=" + net["S"] + ";E=" + net["E"] + ";K=" + passwd
print("Will configure: %s" % cfg)
self.service.getCharacteristics(0xa101)[0].write(cfg.encode(), True)
self.service.getCharacteristics(0xa102)[0].write("C=1".encode(), True)
return True
print("%s cannot see the '%s' network" % (self.name, essid))
return False
def wifi_scan(self):
def _wifi2dict(wifistr):
return kv2dict(wifistr[2:], ",")
if not self.unlock(): return
print("%s is scanning for WiFi networks..." % self.name)
scan = self.service.getCharacteristics(0xa100)[0]
p = -1
n = 0
result = ""
while p < n:
t = scan.read().decode().split(";", 3)
result = result + t[2]
if not t[0].startswith("N=") or not t[1].startswith("P="):
return
n = int(t[0].split("=",2)[1])
p = int(t[1].split("=",2)[1])
# print("read page %d of %d" % (p, n))
return map(_wifi2dict, result.split("&", 50))
def run_command(self, command):
if not self.unlock(): return
run = "P=" + self.pincode + ";N=" + self.pincode + "&&(" + command + ")&"
if len(run) > 128:
print("ERROR: command is too long")
return
#.........这里部分代码省略.........
示例9: range
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [as 别名]
Address = input_str.split("&")[1].split("=")[1]
AES_Key = input_str.split("&")[2].split("=")[1]
Service_UUID = input_str.split("&")[3].split("=")[1]
TotalChar_UUID = [input_str.split("&")[4].split("=")[1][i:i+8] for i in range(0, len(input_str.split("&")[4].split("=")[1]), 8)]
print ("Wallet Address:",Address)
Characteristics = ["Transaction_UUID","Txn_UUID","AddERC20_UUID","Balance_UUID","General_CMD_UUID","General_Data_UUID"]
MainCharacteristics_head = {"Transaction_UUID":TotalChar_UUID[0],"Txn_UUID":TotalChar_UUID[1],"AddERC20_UUID":TotalChar_UUID[2],"Balance_UUID":TotalChar_UUID[3],"General_CMD_UUID":TotalChar_UUID[4],"General_Data_UUID":TotalChar_UUID[5]}
MainCharacteristics = {"Transaction_UUID":"","Txn_UUID":"","AddERC20_UUID":"","Balance_UUID":"","General_CMD_UUID":"","General_Data_UUID":""}
service = p.getServiceByUUID(Service_UUID)
for Character in service.getCharacteristics():
print(Character.uuid)
for x in range(len(MainCharacteristics_head)):
if Character.uuid.getCommonName().startswith(MainCharacteristics_head[Characteristics[x]]):
print(Characteristics[x]," Get!")
MainCharacteristics[Characteristics[x]] = Character.uuid
pass
Balance_GATT = p.getCharacteristics(uuid=MainCharacteristics['Balance_UUID'])[0]
示例10: Scanner
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [as 别名]
devices = Scanner() # Scanner Object
temp=devices.scan(10) # Start Scan
try:
for dev in temp:
if dev.getScanData()[3][2] == "mr. singh": # Check for the target BLE device name
if dev.connectable:
p = Peripheral(dev.addr, "random")
p.setDelegate(ScanDelegate()) # Create internal Object of scandelegate class to handle the notifications
except (RuntimeError, TypeError, NameError):
print "Device not found"
exit(1)
################### Check for the Services and its characteristics #################
print p.getServices()[0]
print p.getServices()[1]
print p.getServices()[2]
Heart_Rate_Measurement = p.getServiceByUUID(0x180D).getCharacteristics()[0]
Body_Sensor_Location = p.getServiceByUUID(0x180D).getCharacteristics()[1]
Heart_Rate_Control_Point = p.getServiceByUUID(0x180D).getCharacteristics()[2]
print Heart_Rate_Measurement , Heart_Rate_Measurement.uuid # Print characteristic and its uuid
print Body_Sensor_Location , Body_Sensor_Location.uuid
print Heart_Rate_Control_Point , Heart_Rate_Control_Point.uuid
################## Print the Value ###########################
body_sensor=["not_selected","Chest","Wrist","Finger","Hand","Ear Lobe","Foot"] # List for body sensor location
try:
ch = p.getServiceByUUID(0x180D).getCharacteristics()[1] # body sensor location characteristics
print ch
if (ch.read()):
print ord(ch.read()) # Print the location
示例11: open
# 需要导入模块: from bluepy.btle import Peripheral [as 别名]
# 或者: from bluepy.btle.Peripheral import getServiceByUUID [as 别名]
print " %s = %s" % (desc, value)
print " "
#Debugging loop
#while 1:
# print "BNDSW %s || SPIRO %s" % (bndsw.getServiceByUUID(UART_UUID).getCharacteristics()[0].read(),
# spiro.getServiceByUUID(UART_UUID).getCharacteristics()[0].read())
#end
#Writing to doc loop
#delete old file for testing
os.system("sudo rm data/data_from_nodes.csv")
file = open("data/data_from_nodes.csv", "a")
while 1:
try:
bndsw_data = str(bndsw.getServiceByUUID(UART_UUID).getCharacteristics()[0].read())
spiro_data = str(spiro.getServiceByUUID(UART_UUID).getCharacteristics()[0].read())
#Drop bad packets data from sensor
if (bndsw_data[0]=='X') and ('Y' in bndsw_data) and ('Z' in bndsw_data):
split_accel_data(bndsw_data)
file.write("N1, " + strftime("%Y-%m-%d %H:%M:%S", gmtime()) + ", " +datax +", " +datay +", " +dataz)
file.write("N2, " + strftime("%Y-%m-%d %H:%M:%S", gmtime()) + ", " + str(spiro_data))
print "."
except KeyboardInterrupt:
print "Python script was killed, closing file..."
file.close()
sys.exit()
end