def _read_bytes(stream): ms = IO.MemoryStream() buf = Array.CreateInstance(System.Byte, 2048) while True: bytes = stream.Read(buf, 0, buf.Length) if bytes == 0: break else: ms.Write(buf, 0, bytes) retval = ms.ToArray() ms.Close() return retval
def image_to_nparray(image_like): '''returns a 3D numpy.ndarray of floats indexed like [x,y,z]''' _shape = (image_like.XSize, image_like.YSize, image_like.ZSize) _array = np.zeros(_shape) _buffer = Array.CreateInstance(Int32, image_like.XSize, image_like.YSize) for z in range(image_like.ZSize): image_like.GetVoxels(z, _buffer) _array[:, :, z] = to_ndarray(_buffer, dtype=c_int32).reshape( (image_like.XSize, image_like.YSize)) return _array
def _dfsu_element_coordinates(dfsu_object): """ Use MIKE SDK method to calc element coords from dfsu_object """ element_coordinates = np.zeros(shape=(dfsu_object.NumberOfElements, 3)) # Convert nodes to .NET System double to input to method xtemp = Array.CreateInstance(System.Double, 0) ytemp = Array.CreateInstance(System.Double, 0) ztemp = Array.CreateInstance(System.Double, 0) # Get element coords elemts_temp = dfs.dfsu.DfsuUtil.CalculateElementCenterCoordinates(dfsu_object, xtemp, ytemp, ztemp) # Place in array; need to get from .NET Array to numpy array for n in range(3): ele_coords_temp = [] for ele in elemts_temp[n+1]: ele_coords_temp.append(ele) element_coordinates[:, n] = ele_coords_temp return element_coordinates
def initialize(self): # Create empty array of four channels. # These are only necessary for initialization channels = Array.CreateInstance(self._api.Functionality, 4) # Initialize each of the channels channels[0] = self._api.Functionality.ARB channels[1] = self._api.Functionality.ARB channels[2] = self._api.Functionality.ARB channels[3] = self._api.Functionality.ARB # Initialise ArbStudio self.call_dll(self._device.Initialize, channels, msg="initializing")
def readScalarIntegerAttribute(dset, name): attr = H5A.open(dset, name) dtype = H5A.getType(attr) buffer = Array.CreateInstance(Int32, 1) H5A.read(attr, dtype, H5Array[Int32](buffer)) fmt = 'The value of the attribute "%s" is %d' print fmt % (name, buffer[0]) H5T.close(dtype) H5A.close(attr) return None
def make_dose_for_grid(dose, image=None): '''returns a 3D numpy.ndarray of doubles matching dose (default) or image grid indexed like [x,y,z]''' if image is not None: row_buffer = Array.CreateInstance(Double, image.ZSize) dose_array = fill_in_profiles(image, dose.GetDoseProfile, row_buffer, c_double) else: # default dose_array = dose_to_nparray(dose) dose_array[np.where(np.isnan(dose_array))] = 0.0 return dose_array
def read(self, streams): count = random.randrange(0, self._maxsize) buffer = Array.CreateInstance(System.Byte, self._maxsize) maxoffset = self._maxsize - count offset = random.randrange(0, maxoffset) toread = min(count, self._currentlength - self._currentoffset) toread = max(0, toread) self._currentoffset += toread self._trace('stream.Read(data, %d, %d)' % (offset, count)) for s in streams: r = s.Read(buffer, offset, count) self._check(r == toread, 'got %d bytes from read. expected %d' % (r, toread))
def readAndDereference(h5file): dsetr = H5D.open(h5file, 'R') dtyper = H5T.copy(H5T_STD_REF_OBJ) dspacer = H5D.getSpace(dsetr) npoints = H5S.getSimpleExtentNPoints(dspacer) nBytes = ObjectReference.SizeInBytes datar = Array.CreateInstance(Byte, npoints * nBytes) H5D.read(dsetr, dtyper, H5Array[Byte](datar)) oref = Array.CreateInstance(ObjectReference, npoints) a = Array.CreateInstance(Byte, nBytes) for i in range(oref.Length): Array.Copy(datar, i * nBytes, a, 0, nBytes) oref[i] = ObjectReference(a) otype = H5R.getObjectType(h5file, oref[0]) if (otype == H5O.ObjectType.GROUP): print 'First dereferenced object is a group.' otype = H5R.getObjectType(h5file, oref[1]) if (otype == H5O.ObjectType.DATASET): print 'Second dereferenced object is a dataset.' dset = H5R.dereference(dsetr, H5R.ReferenceType.OBJECT, oref[1]) dtype = H5D.getType(dset) dtype1 = H5T.copy(H5T_NATIVE_FLOAT) if (H5T.equal(dtype, dtype1)): print 'Datatype of the dataset is H5T_NATIVE_FLOAT.' H5T.close(dtype) H5T.close(dtype1) H5D.close(dset) H5S.close(dspacer) H5T.close(dtyper) H5D.close(dsetr) return None
def testColumnStream(): print 'Verifying ColumnStream against MemoryStream' timer = Stopwatch.StartNew() instance = Instance('ColumnStreamTest') instance.Parameters.MaxVerPages = 1024 instance.Parameters.CircularLog = True instance.Init() bookmark = Array.CreateInstance(System.Byte, 255) try: session = Session(instance) dbid = Api.JetCreateDatabase(session, 'ColumnStream.db', '', CreateDatabaseGrbit.OverwriteExisting) Api.JetBeginTransaction(session) tableid = Api.JetCreateTable(session, dbid, 'table', 0, 100) columndef = JET_COLUMNDEF(coltyp=JET_coltyp.LongBinary) columnid = Api.JetAddColumn(session, tableid, 'LvColumn', columndef, None, 0) Api.JetCloseTable(session, tableid) Api.JetCommitTransaction(session, CommitTransactionGrbit.LazyFlush) tableid = Api.JetOpenTable(session, dbid, 'table', None, 0, OpenTableGrbit.None) for i in xrange(64): runtimer = Stopwatch.StartNew() Api.JetBeginTransaction(session) Api.JetPrepareUpdate(session, tableid, JET_prep.Insert) bookmarksize = Api.JetUpdate(session, tableid, bookmark, 255) Api.JetCommitTransaction(session, CommitTransactionGrbit.LazyFlush) Api.JetGotoBookmark(session, tableid, bookmark, bookmarksize) Api.JetBeginTransaction(session) Api.JetPrepareUpdate(session, tableid, JET_prep.Insert) streams = [ MemoryStream(), ColumnStream(session, tableid, columnid) ] randomOperations(64, streams) Api.JetUpdate(session, tableid) Api.JetCommitTransaction(session, CommitTransactionGrbit.LazyFlush) runtimer.Stop() print '\t%s' % runtimer.Elapsed finally: instance.Dispose() timer.Stop() print '%s' % timer.Elapsed
def array(listArg): dotNetArray = Array.CreateInstance(double, len(listArg)) for idx in range(0, len(listArg)): dotNetArray[idx] = listArg[idx] numSharpArray = ns.NDArray[double]() numSharpArray.Data = dotNetArray numSharpArray.Shape = ns.Shape(dotNetArray.Length) return numSharpArray
def make_segment_mask_for_structure(dose_or_image, structure): '''returns a 3D numpy.ndarray of bools matching dose or image grid indexed like [x,y,z]''' if (structure.HasSegment): mask_array = np.zeros( (dose_or_image.ZSize, dose_or_image.YSize, dose_or_image.XSize)) pre_buffer = System.Collections.BitArray(dose_or_image.ZSize) row_buffer = Array.CreateInstance(bool, dose_or_image.ZSize) return fill_in_profiles(dose_or_image, structure.GetSegmentProfile, row_buffer, c_bool, pre_buffer) else: raise Exception("structure has no segment data")
def ExtractProfile(): #extract profile from image: not used in 3D Tracking [x, y] = ginput(2) x_draw = (x[0], y[0]) y_draw = (x[1], y[1]) plt.plot(x_draw, y_draw) obj.SetPhaseProfileState(True) obj.ExtractPhaseProfile(x[0], x[1], y[0], y[1]) length = obj.GetPhaseProfileLength() bufP = Array.CreateInstance(System.Double, length) obj.GetPhaseProfile(bufP) floatbufP = np.zeros(length, dtype=float) for x in range(0, length - 1): floatbufP[x] = float(bufP[x]) return floatbufP
async def read_gatt_descriptor(self, handle: int, use_cached=False, **kwargs) -> bytearray: """Perform read operation on the specified GATT descriptor. Args: handle (int): The handle of the descriptor to read from. use_cached (bool): `False` forces Windows to read the value from the device again and not use its own cached value. Defaults to `False`. Returns: (bytearray) The read data. """ descriptor = self.services.get_descriptor(handle) if not descriptor: raise BleakError( "Descriptor with handle {0} was not found!".format(handle)) read_result = await wrap_IAsyncOperation( IAsyncOperation[GattReadResult](descriptor.obj.ReadValueAsync( BluetoothCacheMode. Cached if use_cached else BluetoothCacheMode.Uncached)), return_type=GattReadResult, loop=self.loop, ) if read_result.Status == GattCommunicationStatus.Success: reader = DataReader.FromBuffer(IBuffer(read_result.Value)) output = Array.CreateInstance(Byte, reader.UnconsumedBufferLength) reader.ReadBytes(output) value = bytearray(output) logger.debug("Read Descriptor {0} : {1}".format(handle, value)) else: if read_result.Status == GattCommunicationStatus.ProtocolError: raise BleakDotNetTaskError( "Could not get GATT characteristics for {0}: {1} (Error: 0x{2:02X})" .format( descriptor.uuid, _communication_statues.get(read_result.Status, ""), read_result.ProtocolError, )) else: raise BleakError( "Could not read Descriptor value for {0}: {1}".format( descriptor.uuid, _communication_statues.get(read_result.Status, ""), )) return value
def Decompress(compressed): with MemoryStream(compressed.Length) as inputStream: inputStream.Write(compressed, 0, compressed.Length) inputStream.Seek(0, SeekOrigin.Begin) with MemoryStream() as outputStream: with DeflateStream(inputStream, CompressionMode.Decompress) as deflateStream: buffer = Array.CreateInstance(Byte, 4096) bytesRead = deflateStream.Read(buffer, 0, buffer.Length) outputStream.Write(buffer, 0, bytesRead) while bytesRead != 0: bytesRead = deflateStream.Read(buffer, 0, buffer.Length) outputStream.Write(buffer, 0, bytesRead) return outputStream.ToArray()
def Conv2Array(filename, rowoffset, delim): legnames = [] data = [] for row in csv.reader(open(filename), delimiter=delim): data.append(row) headers = data[0] # contains the column names # determine the number of measured parameters numvar = len(headers) # determine the number of rows of the CSV table numrows = len(data) entries = numrows - 1 print 'Number of Vars :', numvar print 'Number of Entries :', entries # initialize 2D array to store all parameter values values = Array.CreateInstance(float, numrows - rowoffset, numvar) # define empty list with ... entries typelist = [None] * numvar # write values from table into array for i in range(0, numrows - rowoffset, 1): # write the data into array tmp = data[i + rowoffset] for k in range(0, len(tmp), 1): # convert "," to "." tmp[k] = str.replace(tmp[k], ',', '.') try: values[i, k] = float(tmp[k]) if (i == 0): typelist[ k] = 'float' # type of data for current column = float except: values[i, k] = float('nan') if (i == 0): typelist[ k] = 'str' # type of data for current column = str print typelist # create legend names for i in range(0, numvar, 1): legname_tmp = headers[i] legnames.append(legname_tmp) return values, legnames, numvar, entries, typelist
def XlsWriter(self): ex = Excel.ApplicationClass() ex.Visible = True ex.DisplayAlerts = False workbook = ex.Workbooks.Add() workbook.SaveAs(self.dirpath + "\\reportFamilies.xlsx") ws = workbook.Worksheets[1] nbr_row = 1 for sub_lst in self.full_lstP: nbr_col = len(sub_lst) xlrange = ws.Range[ws.Cells(nbr_row, 1), ws.Cells(nbr_row, len(sub_lst))] a = Array.CreateInstance(object, 1, len(sub_lst)) b = Array.CreateInstance(object, 1, len(sub_lst)) for index, i in enumerate(sub_lst): # if i is string if isinstance(i, str): a[0, index] = i #else i is a ParameterProp objet else: a[0, index] = i._pname if i._pisinstance == False: b[0, index] = 6 elif i._pisinstance == True: b[0, index] = 8 else: b[0, index] = None #copy Array in range xlrange.Value2 = a for cell, color_index in zip(xlrange, b): cell.Interior.ColorIndex = color_index nbr_row += 1 used_range = ws.UsedRange for column in used_range.Columns: column.AutoFit() workbook.Save()
def createDatasetWithCompoundType(h5file): # component name -> (offset, size, type) ht = { 'a_name': (0, 4, H5T_NATIVE_INT), 'b_name': (4, 4, H5T_NATIVE_FLOAT), 'c_name': (8, 8, H5T_NATIVE_DOUBLE) } sizeof = 0 for k in ht.keys(): sizeof += ht[k][1] dtype = H5T.create(H5T.CreateClass.COMPOUND, sizeof) for k in ht.keys(): H5T.insert(dtype, k, ht[k][0], ht[k][2]) npoints = 10 shape = Array[Int64]((npoints,)) dspace = H5S.create_simple(shape.Length, shape) dset = H5D.create(h5file, 'ArrayOfStructures', dtype, dspace) # create an array of Byte # use BitConverter to get Byte representations shape = Array[Int64]((npoints*sizeof,)) byteArray = Array.CreateInstance(Byte, shape) for i in range(npoints): offset = i*sizeof a = Int32(i) Array.Copy(BitConverter.GetBytes(a), 0, byteArray, offset+ht['a_name'][0], ht['a_name'][1]) b = Single(i*i) Array.Copy(BitConverter.GetBytes(b), 0, byteArray, offset+ht['b_name'][0], ht['b_name'][1]) c = Double(1.0/(i+1.0)) Array.Copy(BitConverter.GetBytes(c), 0, byteArray, offset+ht['c_name'][0], ht['c_name'][1]) H5D.write(dset, dtype, H5Array[Byte](byteArray)) H5S.close(dspace) H5T.close(dtype) return dset
def receive(self): """listen to a message until received one""" if self.socket.State != WebSocketState.Open: raise RuntimeError('Connection is not open.') chunks = [] while True: # print('receive chunk') buffer = Array.CreateInstance(Byte, RECEIVE_CHUNK_SIZE) task = self.socket.ReceiveAsync( ArraySegment[Byte](buffer), self.token) task.Wait() chunk = Encoding.UTF8.GetString(buffer) chunks.append(chunk.rstrip('\x00')) if task.Result.EndOfMessage: return ''.join(chunks)
def getIntensity32fImage(contrast, width, height): #get float intensity image if contrast == 'lambda1': obj.SelectDisplayWL(2048) elif contrast == 'lambda2': obj.SelectDisplayWL(4096) else: obj.SelectDisplayWL(2048) size = width * height bufP = Array.CreateInstance(System.Single, size) obj.GetIntensity32fImage(bufP) floatbufP = np.zeros(size, dtype=float) for x in range(0, size - 1): floatbufP[x] = float(bufP[x]) out = np.reshape(floatbufP, (height, width)) return out
def parse_eventargs(event_args): bdaddr = _format_bdaddr(event_args.BluetoothAddress) uuids = [] for u in event_args.Advertisement.ServiceUuids: uuids.append(u.ToString()) data = {} for m in event_args.Advertisement.ManufacturerData: md = IBuffer(m.Data) b = Array.CreateInstance(Byte, md.Length) reader = DataReader.FromBuffer(md) reader.ReadBytes(b) data[m.CompanyId] = bytes(b) local_name = event_args.Advertisement.LocalName return BLEDevice(bdaddr, local_name, event_args, uuids=uuids, manufacturer_data=data)
def start_listening(self): """Starts listening asynchronously while the socket is open. The inter-thread synchronization between this and the async reception threads is sync'd with a manual reset event.""" try: LOGGER.debug('About to start listening, socket state: %s', self.socket.State) while self.socket and self.socket.State == WebSocketState.Open: mre = ManualResetEventSlim(False) content = [] buffer = Array.CreateInstance(Byte, RECEIVE_CHUNK_SIZE) self.receive_chunk_async( None, dict(buffer=buffer, content=content, mre=mre)) LOGGER.debug('Waiting for messages...') try: mre.Wait(self.factory.manager.cancellation_token) except SystemError: LOGGER.debug( 'Cancellation detected on listening thread, exiting...' ) break try: message_payload = ''.join(content) LOGGER.debug('Message reception completed|<pre>%s</pre>', message_payload) self.on_message(message_payload) except Exception: LOGGER.exception( 'Exception on start_listening while trying to handle message received.' + 'It could indicate a bug in user code on message handlers. Message skipped.' ) except Exception: LOGGER.exception( 'Exception on start_listening, processing will be aborted') raise finally: LOGGER.debug('Leaving the listening thread')
def addSimpleFloatAttribute(dset): shape = Array[Int64]((2, 3)) matrix = Array.CreateInstance(Single, shape) for row in range(matrix.GetLength(0)): for col in range(matrix.GetLength(1)): matrix[row, col] = -1 dspace = H5S.create_simple(shape.Length, shape) dtype = H5T.copy(H5T_NATIVE_FLOAT) attr = H5A.create(dset, 'Float attribute', dtype, dspace) H5A.write(attr, dtype, H5Array[Single](matrix)) H5A.close(attr) H5T.close(dtype) H5S.close(dspace) return None
def load_waveforms(self): if not self.waveforms: # Must have at least one waveform, add one with 0V self.add_waveform(np.array([0, 0, 0, 0])) # Initialize array of waves waveforms = Array.CreateInstance(self._api.WaveformStruct, len(self.waveforms)) # We have to create separate wave instances and load them into # the waves array one by one for k, waveform_array in enumerate(self.waveforms): wave = self._api.WaveformStruct() wave.Sample = waveform_array waveforms[k] = wave self.parent.call_dll(self.channel_api.LoadWaveforms, waveforms, msg="loading waveforms")
def exc_writearray(origin = "A3", worksheetname= "Sheets"): originnr = [i for i in origin if i.isdigit()][0] end = len(ex_row) - 1 + int(originnr) xlapp = Marshal.GetActiveObject('Excel.Application') worksheet = xlapp.sheets(worksheetname) #Name of the Excel Worksheet xlrange_id = worksheet.Range["I" + str(originnr), "I" + str(end)] #from System.Reflection import Missing from System import Array array_id = Array.CreateInstance(object, len(ex_row), 1) # set array_id with values from dic_sheetGuid for i,j in zip(range(len(ex_row)), ex_row): if j[0] in dic_sheetGuid: array_id[i, 0] = dic_sheetGuid[j[0]] #write array to cellrange_sheetid if (xlrange_id.Value2.GetLength(0), xlrange_id.Value2.GetLength(1)) \ == (array_id.GetLength(0), array_id.GetLength(1)): # (7,1) == ( 7,1) xlrange_id.Value2 = array_id Marshal.ReleaseComObject(xlapp) return True
def set_fluence_nparray(beam, shaped_fluence, beamlet_size_mm=2.5): """sets optimal fluence in beam given numpy array and beamlet size (asserts square fluence, and zero collimator rotation).""" # assumes all fluence is square with isocenter at center of image # TODO: implement functionality below to remove assertions assert beamlet_size_mm == 2.5, "beamlet sizes of other than 2.5 mm are not implemented" assert shaped_fluence.shape[0] == shaped_fluence.shape[1], "non-square fluence not implemented" assert beam.ControlPoints[0].CollimatorAngle == 0.0, "non-zero collimator angle not implemented" _buffer = Array.CreateInstance(System.Single, shaped_fluence.shape[0], shaped_fluence.shape[1]) # note: the shape -1, then divide by 2.0 gives desired center of corner beamlet (half pixel shift) x_origin = - float(shaped_fluence.shape[0] - 1) * beamlet_size_mm / 2.0 y_origin = + float(shaped_fluence.shape[1] - 1) * beamlet_size_mm / 2.0 for i in range(shaped_fluence.shape[0]): for j in range(shaped_fluence.shape[1]): _buffer[i, j] = shaped_fluence[i, j] fluence = Fluence(_buffer, x_origin, y_origin) beam.SetOptimalFluence(fluence)
def process(context): filename = context.Request.Url.AbsolutePath if not filename: filename = "index.html" if filename[0] == '/': filename = filename[1:] print(filename) filename = Path.Combine(root, filename) print(filename) if not File.Exists(filename): context.Response.Abort() return input = FileStream(filename, FileMode.Open) bytes = Array.CreateInstance(Byte, 1024 * 16) nbytes = input.Read(bytes, 0, bytes.Length) while nbytes > 0: context.Response.OutputStream.Write(bytes, 0, nbytes) nbytes = input.Read(bytes, 0, bytes.Length) input.Close() context.Response.OutputStream.Close()
def testCorrectOverloadSelection(self): """ Test correct overloading selection for common types. """ from System.Drawing import Font from System import (String, Double, Single, Int16, Int32, Int64) from System import Math substr = String("substring") self.assertTrue( substr.Substring(2) == substr.Substring.__overloads__[Int32](Int32( 2))) self.assertTrue( substr.Substring(2, 3) == substr.Substring.__overloads__[ Int32, Int32](Int32(2), Int32(3))) for atype, value1, value2 in zip([Double, Single, Int16, Int32, Int64], [1.0, 1.0, 1, 1, 1], [2.0, 0.5, 2, 0, -1]): self.assertTrue( Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype( value1))) self.assertTrue( Math.Abs(value1) == Math.Abs.__overloads__[atype](atype( value1))) self.assertTrue( Math.Max(atype(value1), atype(value2)) == Math.Max.__overloads__[atype, atype](atype(value1), atype(value2))) if (atype is Int64) and six.PY2: value2 = long(value2) self.assertTrue( Math.Max(atype(value1), value2) == Math.Max.__overloads__[ atype, atype](atype(value1), atype(value2))) clr.AddReference("System.Runtime.InteropServices") from System.Runtime.InteropServices import GCHandle, GCHandleType from System import Array, Byte CSArray = Array.CreateInstance(Byte, 1000) handler = GCHandle.Alloc(CSArray, GCHandleType.Pinned)
def readDataSet(dset): dspace = H5D.getSpace(dset) dims = H5S.getSimpleExtentDims(dspace) print 'dataset rank %d, dimensions %d x %d' % (dims.Length, dims[0], dims[1]) mspace = H5S.create_simple(dims.Length, dims) dtype = H5T.copy(H5T_NATIVE_INT) data = Array.CreateInstance(Int32, dims) H5D.read(dset, dtype, mspace, dspace, H5P_DEFAULT, H5Array[Int32](data)) print 'Dataset: ' for row in range(data.GetLength(0)): for col in range(data.GetLength(1)): print '%d ' % (data[row, col]), print '' print '' # dataset rank 2, dimensions 10 x 5 # chunk rank 2, dimensions 2 x 5 # # Dataset: # 1 1 1 3 3 # 1 1 1 3 3 # 1 1 1 0 0 # 2 0 0 0 0 # 2 0 0 0 0 # 2 0 0 0 0 # 2 0 0 0 0 # 2 0 0 0 0 # 2 0 0 0 0 # 2 0 0 0 0 H5T.close(dtype) H5S.close(mspace) H5S.close(dspace) return None
def readChunk(dset): fspace = H5D.getSpace(dset) cplist = H5D.getCreatePropertyList(dset) if H5P.getLayout(cplist) == H5D.Layout.CHUNKED: cdims = H5P.getChunk(cplist, 2) print 'chunk rank 2, dimensions %d x %d' % (cdims[0], cdims[1]) dtype = H5T.copy(H5T_NATIVE_INT) mspace = H5S.create_simple(cdims.Length, cdims) offset = Array[Int64]((2, 0)) count = Array[Int64]((cdims[0], cdims[1])) H5S.selectHyperslab(fspace, H5S.SelectOperator.SET, offset, count) data = Array.CreateInstance(Int32, cdims) H5D.read(dset, dtype, mspace, fspace, H5P_DEFAULT, H5Array[Int32](data)) print 'Chunk: ' for row in range(data.GetLength(0)): for col in range(data.GetLength(1)): print '%d ' % (data[row, col]), print '' print '' # Chunk: # 1 1 1 0 0 # 2 0 0 0 0 H5S.close(mspace) H5T.close(dtype) H5S.close(fspace) return None
async def read_gatt_char(self, _uuid: str, use_cached=False, **kwargs) -> bytearray: """Perform read operation on the specified GATT characteristic. Args: _uuid (str or UUID): The uuid of the characteristics to read from. use_cached (bool): `False` forces Windows to read the value from the device again and not use its own cached value. Defaults to `False`. Returns: (bytearray) The read data. """ characteristic = self.services.get_characteristic(str(_uuid)) if not characteristic: raise BleakError("Characteristic {0} was not found!".format(_uuid)) read_result = await wrap_IAsyncOperation( IAsyncOperation[GattReadResult]( characteristic.obj.ReadValueAsync( BluetoothCacheMode.Cached if use_cached else BluetoothCacheMode.Uncached ) ), return_type=GattReadResult, loop=self.loop, ) if read_result.Status == GattCommunicationStatus.Success: reader = DataReader.FromBuffer(IBuffer(read_result.Value)) output = Array.CreateInstance(Byte, reader.UnconsumedBufferLength) reader.ReadBytes(output) value = bytearray(output) logger.debug("Read Characteristic {0} : {1}".format(_uuid, value)) else: raise BleakError( "Could not read characteristic value for {0}: {1}".format( characteristic.uuid, read_result.Status ) ) return value