def encode_transaction(self, input_num = None): # Start transaction trans = bytearray() trans += ctypes.c_uint32(self.version) trans += ctypes.c_uint8(len(self.inputs)) # Go through inputs x=0 for item in self.inputs: trans += item['txid'][::-1] trans += ctypes.c_uint32(item['vout']) if input_num == None or input_num == x: trans += self.encode_vint(len(item['sigscript'])) trans += item['sigscript'] else: trans += unhexlify('00') trans += item['sequence'] x += 1 # Go through outputs trans += ctypes.c_uint8(len(self.outputs)) for item in self.outputs: # Add output trans += ctypes.c_uint64(int(item['amount'] * 1e8)) trans += self.encode_vint(len(item['script'])) trans += item['script'] # Finish encoding trans += self.timelock return trans
def encodeRequest(cls, username, password, uuid, ownerUuid, isOwnerConnection): clientMessage = ClientMessage() clientMessage.setOperationType(ClientAuthenticationCodec.REQUEST_TYPE) clientMessage.setRetryable(ClientAuthenticationCodec.RETRYABLE) clientMessage.set(username) clientMessage.set(password) uuid_isNull=None if uuid is None: uuid_isNull = True uuid_isNull=bytearray(ctypes.c_uint8(uuid_isNull)) clientMessage.set(uuid_isNull) else: uuid_isNull= False uuid_isNull=bytearray(ctypes.c_uint8(uuid_isNull)) clientMessage.set(uuid_isNull) clientMessage.set(uuid) ownerUuid_isNull=None if ownerUuid is None: ownerUuid_isNull = True ownerUuid_isNull=bytearray(ctypes.c_uint8(ownerUuid_isNull)) clientMessage.set(ownerUuid_isNull) else: ownerUuid_isNull= False ownerUuid_isNull=bytearray(ctypes.c_uint8(ownerUuid_isNull)) clientMessage.set(ownerUuid_isNull) clientMessage.set(ownerUuid) clientMessage.set(isOwnerConnection) clientMessage.updateSize() return clientMessage
def servoSetPosition(self, servo_id, angle): #sets servo to input position global COMMAND_HEADER byte_1 = bytes(c_uint8(208+ servo_id)) byte_2 = bytes(c_uint8(angle)) self.ser.write(COMMAND_HEADER + byte_1 + byte_2) reply = binascii.hexlify(self.ser.read(size=3)) return str(reply, 'ascii') #return reply as ascii string
def set_parameters(self): """ set superK control parameters. Most of these should not be configurable and hard-coded for safety. """ if self.isConnected: SMELLIELogger.debug('SNODROP DEBUG: SuperKDriver.set_parameters()') superKControls = superKControlStructure() superKControls.trigLevelSetpointmV = c_uint16(1000) superKControls.displayBacklightPercent = c_uint8(0) superKControls.trigMode = c_uint8(1) superKControls.internalPulseFreqHz = c_uint16(0) superKControls.burstPulses = c_uint16(1) superKControls.watchdogIntervalSec = c_uint8(0) superKControls.internalPulseFreqLimitHz = c_uint32(24000) #doesn't do anything. Possibly a manufacturer option disabled in firmware. setSuperKControls(self.COMPort,superKControls) #check parameters have been set correctly: new_superKControls=self.get_parameters() if (superKControls.trigLevelSetpointmV!=new_superKControls.trigLevelSetpointmV or superKControls.displayBacklightPercent!=new_superKControls.displayBacklightPercent or superKControls.trigMode!=new_superKControls.trigMode or superKControls.internalPulseFreqHz!=new_superKControls.internalPulseFreqHz or superKControls.burstPulses!=new_superKControls.burstPulses or superKControls.watchdogIntervalSec!=new_superKControls.watchdogIntervalSec or superKControls.internalPulseFreqLimitHz!=new_superKControls.internalPulseFreqLimitHz): SMELLIELogger.warn('SNODROP WARN: Error upon setting SuperK control bits. Specified values have not all been set. Check system.') raise SuperKDriverHWError("Error upon setting SuperK control bits. Specified values have not all been set. Check system.{}.") else: raise SuperKDriverLogicError("SuperK port not open.")
def binary(self, fordevice = False): hdr = bytes(c_uint8(self.no_keys)) + bytes(c_uint8(self.no_layers)) l = b''.join(map(lambda x: b''.join(map(lambda x: x.binary(fordevice), x)), self.layers)) if fordevice: return hdr + l else: return hdr + l + bytes(map(as_unsigned, self.parents))
def encodeMessage(self): #since Python only uses ints and longs and does weird memory stuff, we need to wrap them here using the C types newVersion=ctypes.c_uint8(self.version) newFlag=ctypes.c_uint8(self.flag) newType=ctypes.c_uint16(self.optype) newCorrelation=ctypes.c_uint32(self.correlation) newPartition=ctypes.c_int32(self.partition) byteArray=bytearray(newVersion)+bytearray(newFlag)+bytearray(newType)+bytearray(newCorrelation)+bytearray(newPartition) netSize=4+len(byteArray)+2 self.HEADER_SIZE=netSize if self.extension is not None: netSize+=len(self.extension) self.DATA_OFFSET=netSize if self.payload is not None: netSize+=len(self.payload) self.FRAME_SIZE=netSize newSize=ctypes.c_int32(self.FRAME_SIZE) newOffset=ctypes.c_uint16(self.DATA_OFFSET) byteArray=bytearray(newSize)+byteArray+bytearray(newOffset) if self.extension is not None: byteArray+=self.extension if self.payload is not None: byteArray+=self.payload return byteArray
def dcMove(self, motor_id, direction, speed): #turns ON motor giving direction and speed global COMMAND_HEADER byte_1 = bytes(c_uint8( 128 + direction )) byte_2 = bytes(c_uint8(speed*32 + motor_id)) self.ser.write(COMMAND_HEADER + byte_1 + byte_2) reply = binascii.hexlify(self.ser.read(size=3)) return str(reply, 'ascii') #return reply as ascii string
def writeLength(value): return [ ctypes.c_uint8((value >> 24) & 0xFF).value, ctypes.c_uint8((value >> 16) & 0xFF).value, ctypes.c_uint8((value >> 8) & 0xFF).value, ctypes.c_uint8(value & 0xFF).value ]
def __init__(self): try: if sys.platform == 'darwin': raise OSError self.__DCONDLL = ctypes.windll.LoadLibrary(os.getcwd() + '\DCON_PC.dll') self.__UARTDLL = ctypes.windll.LoadLibrary(os.getcwd() + '\Uart.dll') mode = 'Hardware driver .dll found' except OSError: self.__DCONDLL = USB87P4Simulator('DCON') self.__UARTDLL = USB87P4Simulator('UART') mode = 'OSError, enter simulation mode' except AttributeError: self.__DCONDLL = USB87P4Simulator('DCON') self.__UARTDLL = USB87P4Simulator('UART') mode = 'Hardware not present, enter simulation mode' print mode self.__dwBaudRate = ctypes.c_uint32(115200) self.__iAddress = ctypes.c_int16(2) self.__iSlot = ctypes.c_int16(-1) self.__iCheckSum = ctypes.c_int16(0) self.__iTimeOut = ctypes.c_int16(100) self.__cParity = ctypes.c_uint8(0) self.__cStop = ctypes.c_uint8(0) self.__cData = ctypes.c_uint8(8) self.__iAOTotalCh = ctypes.c_int16(4) # com port 7 as in TPS41 layout self.__cComPort = ctypes.c_uint8(7)
def testEncodingWithExtension(self): msg=ClientMessage() vr=0 optype=200 corrID=0 parID=-1 msg.version=vr msg.optype=optype msg.correlation=corrID msg.partition=parID msg.addExtension(bytearray(ctypes.c_uint32(4203239))) frame = bytearray() #Create a byte array of size 18 frame+=bytearray(ctypes.c_int32(18+4)) frame+=bytearray(ctypes.c_uint8(vr)) frame+=bytearray(ctypes.c_uint8(192)) frame+=bytearray(ctypes.c_uint16(optype)) frame+=bytearray(ctypes.c_int32(corrID)) frame+=bytearray(ctypes.c_int32(parID)) frame+=bytearray(ctypes.c_uint16(22)) frame+=bytearray(ctypes.c_uint32(4203239)) encodedMsg=msg.encodeMessage() self.assertEqual(frame,encodedMsg)
def testEncoding(self): msg=ClientMessage() vr=0 optype=200 corrID=0 parID=-1 msg.setVersion(vr) msg.setFlagBoth() msg.setOperationType(200) msg.correlation=corrID msg.setPartition(parID) frame = bytearray() #Create a byte array of size 18 frame+=bytearray(ctypes.c_int32(18)) frame+=bytearray(ctypes.c_uint8(vr)) frame+=bytearray(ctypes.c_uint8(192)) frame+=bytearray(ctypes.c_uint16(optype)) frame+=bytearray(ctypes.c_int32(corrID)) frame+=bytearray(ctypes.c_int32(parID)) frame+=bytearray(ctypes.c_uint16(18)) self.assertEqual(frame,msg.encodeMessage())
def _open_usb(self, serial): """Open a USB connection to the controller with the specified serial number.""" handle=ctypes.c_ulong() if dll.FT_OpenEx(serial, 1, ctypes.byref(handle)): raise RuntimeError('USB open failed.') if dll.FT_SetBaudRate(handle ,ctypes.c_ulong(115200)): raise RuntimeError('USB baud rate failed.') if dll.FT_SetDataCharacteristics(handle, ctypes.c_uint8(8), ctypes.c_uint8(0), ctypes.c_uint8(0)): raise RuntimeError('USB set data format failed.') time.sleep(0.1) if dll.FT_Purge(handle, ctypes.c_ulong(1|2)): raise RuntimeError('USB purge failed.') time.sleep(0.1) if dll.FT_ResetDevice(handle): raise RuntimeError('USB reset failed.') if dll.FT_SetFlowControl(handle, ctypes.c_ushort(0x0100), ctypes.c_uint8(0), ctypes.c_uint8(0)): raise RuntimeError('USB set flow control failed.') if dll.FT_SetRts(handle): raise RuntimeError('USB set RTS failed.') if dll.FT_SetTimeouts(handle,1000,0): raise RuntimeError('USB set timeouts failed.') self.usb = handle
def hscryptkdf(password, dklen, maxmem, maxmemfrac, maxtime, params = None, saltsz = 32, nocheck = False): dk = create_string_buffer(dklen) # get lib's param size psz = _hgetparamsize() # check length of params if params is not None and len(params) < (psz + saltsz): raise Exception('For this build of the scrypt lib the params are %s/%s bytes! The salt size is %s.' % (len(params), psz + saltsz, saltsz)) if params is None: print('creating param bytes') params = create_string_buffer(psz + saltsz) recover = 0 else: print('using param bytes') params = c_char_p(params) recover = 1 if nocheck: nocheck = 1 else: nocheck = 0 rcode = _hscryptkdf( c_char_p(password), c_size_t(len(password)), dk, c_size_t(dklen), c_size_t(saltsz), c_double(maxmem), c_double(maxmemfrac), c_double(maxtime), params, c_uint8(recover), c_uint8(nocheck) ) if recover == 0: # convert from string buffer into bytes object params = bytes(params) return (rcode, bytes(dk), params)
def stepperMove(self, motor_id, steps): #turns on stepper motor for input number of steps global COMMAND_HEADER byte_1 = bytes(c_uint8(240 + motor_id)) byte_2 = bytes(c_uint8(steps)) self.ser.write(COMMAND_HEADER + byte_1 + byte_2) reply = binascii.hexlify(self.ser.read(size=3)) return str(reply, 'ascii') #return reply as ascii string
def raw_number_neg(self, num): """ >>> p = Parser('') >>> p.raw_number_neg(-1) 255 >>> p.raw_number_neg(-12) 244 >>> p.raw_number_neg(-126) 130 >>> p.raw_number_neg(-127) 65409 >>> p.raw_number_neg(-200) 65336 >>> p.raw_number_neg(-40000) # doctest: +ELLIPSIS 4294927296... >>> p.raw_number_neg(1) # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ValueError: Invalid logic, number should not be positive """ if num >= 0: raise ValueError('Invalid logic, number should not be positive') #print (ctypes.c_uint8(-num).value, -num, int(0xff/2)) if ctypes.c_uint8(-num).value == -num and -num < int(0xff/2): return ctypes.c_uint8(num).value if ctypes.c_uint16(-num).value == -num and -num < int(0xffff/2): return ctypes.c_uint16(num).value if ctypes.c_uint32(-num).value == -num and -num < int(0xffffffff/2): return ctypes.c_uint32(num).value return ctypes.c_uint64(num).value
def _generate_signal_data(self): if self._signals_generate: return for s in self.signals: rate = self.signals[s].rate value = self.signals[s].value dv = PyValueImp() dv.digital = c.c_uint8(1) data = PySignalImp(0.0, float(rate.duration), dv, value.type_id, s, PyHistoryImp(0.0), None) orig_data = data runtime = 0 while runtime < self.length: next_in = float(rate.next()) runtime += next_in dv = PyValueImp() dv.digital = c.c_uint8(value.next_value()) next_data = PySignalImp(runtime, float(rate.duration), dv, value.type_id, s, PyHistoryImp(0.0), None) data.next = c.pointer(next_data) data = next_data self._data[s] = orig_data self._signals_generate = True for x in self._data: register_signal(c.pointer(self._data[x]))
def convert_uint32_to_array(val): uint16_data = c_uint32(val) byte0 = c_uint8((uint16_data.value & 0x000000FF)) byte1 = c_uint8((uint16_data.value & 0x0000FF00) >> 8) byte2 = c_uint8((uint16_data.value & 0x00FF0000) >> 16) byte3 = c_uint8((uint16_data.value & 0xFF000000) >> 24) return [byte0.value, byte1.value, byte2.value, byte3.value]
def diff_iterate(self, offset, length, from_snapshot, iterate_cb, include_parent = True, whole_object = False): """ Iterate over the changed extents of an image. This will call iterate_cb with three arguments: (offset, length, exists) where the changed extent starts at offset bytes, continues for length bytes, and is full of data (if exists is True) or zeroes (if exists is False). If from_snapshot is None, it is interpreted as the beginning of time and this generates all allocated extents. The end version is whatever is currently selected (via set_snap) for the image. Raises :class:`InvalidArgument` if from_snapshot is after the currently set snapshot. Raises :class:`ImageNotFound` if from_snapshot is not the name of a snapshot of the image. :param offset: start offset in bytes :type offset: int :param length: size of region to report on, in bytes :type length: int :param from_snapshot: starting snapshot name, or None :type from_snapshot: str or None :param iterate_cb: function to call for each extent :type iterate_cb: function acception arguments for offset, length, and exists :param include_parent: True if full history diff should include parent :type include_parent: bool :param whole_object: True if diff extents should cover whole object :type whole_object: bool :raises: :class:`InvalidArgument`, :class:`IOError`, :class:`ImageNotFound` """ if from_snapshot is not None and not isinstance(from_snapshot, str): raise TypeError('client must be a string') RBD_DIFF_CB = CFUNCTYPE(c_int, c_uint64, c_size_t, c_int, c_void_p) cb_holder = DiffIterateCB(iterate_cb) cb = RBD_DIFF_CB(cb_holder.callback) ret = self.librbd.rbd_diff_iterate2(self.image, c_char_p(from_snapshot), c_uint64(offset), c_uint64(length), c_uint8(include_parent), c_uint8(whole_object), cb, c_void_p(None)) if ret < 0: msg = 'error generating diff from snapshot %s' % from_snapshot raise make_ex(ret, msg)
def set_port_line_direction_map(self, mapp, port=0): # mapp: np array or list with 8 0's or 1's # 0 = input, 1 = output port = ctypes.c_uint8(port) mapp = np.asarray(mapp) assert len(mapp)==8 r = np.arange(7,-1,-1) _map = np.sum(2**r * mapp).astype(int) bitmap = ctypes.c_uint8(_map) errChk(ni845x_dll.ni845xDioSetPortLineDirectionMap(self.dev_handle, port, bitmap))
def __init__(self, serial_number=None): # USB device parameters self.vendor_id = 0x0004 self.product_id = 0x0002 self.bulkout_ep_address = 0x01 self.bulkin_ep_address = 0x82 self.buffer_out_size = 64 self.buffer_in_size = 64 self.serial_number = serial_number USBDevice.USB_Device.__init__(self, self.vendor_id, self.product_id, self.bulkout_ep_address, self.bulkin_ep_address, self.buffer_out_size, self.buffer_in_size, self.serial_number) # USB Command IDs self.USB_CMD_GET_STATE = ctypes.c_uint8(1) self.USB_CMD_SET_STATE = ctypes.c_uint8(2) self.USBPacketOut = USBPacketOut_t() self.USBPacketIn = USBPacketIn_t() # self.Motor = [] # for MotorN in range(_motor_num): # self.Motor.append({'Frequency' : 0, # 'FrequencyMax' : FREQUENCY_MAX, # 'Position' : 0, # 'PositionMin' : POSITION_MIN, # 'PositionMax' : POSITION_MAX, # 'PositionSetPoint' : 0, # 'Direction' : 0}) # Parameters self.frequency_max = 30000 self.position_min = 0 self.position_max = 44000 self.steps_per_mm = 5000/25.4 # 5000 steps per inch # 25.4 mm per inch self.steps_per_radian = 200 # Change to actual number! self.axis_x = 0 self.axis_y = 1 self.axis_theta = 2 self.x_vel_mm = 0 self.x_vel_steps = 0 self.y_vel_mm = 0 self.y_vel_steps = 0 self.x_pos_mm = 0 self.x_pos_steps = 0 self.y_pos_mm = 0 self.y_pos_steps = 0
def draw_color(self): r = ctypes.c_uint8() g = ctypes.c_uint8() b = ctypes.c_uint8() a = ctypes.c_uint8() errcheck( _SDL.SDL_GetRenderDrawColor( self._renderer, ctypes.byref(r), ctypes.byref(g), ctypes.byref(b), ctypes.byref(a) ) ) return (r.value, g.value, b.value, a.value)
def requestTargetSymbols(self, timeout=1): targetSymbols = dict() self._ResponseFifo.queue.clear() f = ComFrame() f.interface = CALMEAS_INTERFACE f.mid = CALMEAS_ID_META f.setData([]) self._comhandler.sendFrame(f) try: meta = getResponseData(self._ResponseFifo, timeout) except Queue.Empty: raise Exception('Timeout trying to get meta data.') for index, symbol in enumerate(meta): logging.info("Getting symbol with index {}".format(index)) s = Symbol() s.index = index c_basetype = self.getBaseType(symbol[0])[0] s.setDatatype( SymbolDataType(self.getBaseType(symbol[0])[1]) ) s.nameAddress = symbol[1] s.address = symbol[2] s.descAddress = symbol[3] f.mid = CALMEAS_ID_SYMBOL_NAME f.setData([ctypes.c_uint8(index)]) self._comhandler.sendFrame(f) logging.debug('Waiting for name of {}'.format(index)) try: s.name = getResponseData(self._ResponseFifo, timeout) except Queue.Empty: raise Exception('Timeout trying to get symbol names.') f.mid = CALMEAS_ID_SYMBOL_DESC f.setData([ctypes.c_uint8(index)]) self._comhandler.sendFrame(f) logging.debug('Waiting for description of {}'.format(index)) try: s.desc = str(getResponseData(self._ResponseFifo, timeout)) except Queue.Empty: raise Exception('Timeout trying to get symbol description.') targetSymbols[s.name] = s self.targetSymbols = targetSymbols return self.targetSymbols
def payload_decrypt(self, buffer, key, address, dir, sequenceCounter): decbuffer = (c_uint8 * 64)() self.Crypto.LoRaMacPayloadDecrypt( create_string_buffer(bytes(buffer)), c_uint8(len(buffer)), create_string_buffer(bytes(key)), c_uint32(address), c_uint8(dir), c_uint32(sequenceCounter), byref(decbuffer), ) return hexlify(bytes(decbuffer)[: len(buffer)]).decode()
def PayloadEncrypt(self, buf, key, address, dir, sequenceCounter): bufferBin = unhexlify(buf) keyBin = unhexlify(key) addressInt = int(address, 16) enBuffer = (c_uint8 * 64)() self.Crypto.LoRaMacPayloadEncrypt(create_string_buffer(bytes(bufferBin)), c_uint8(len(bufferBin)), create_string_buffer(bytes(keyBin)), c_uint32(addressInt), c_uint8(dir), c_uint32(sequenceCounter), byref(enBuffer)) return hexlify(bytes(enBuffer)[:len(bufferBin)]).decode()
def __init__(self): self.lock = threading.Lock() rospy.init_node('listener', anonymous=True) rospy.Subscriber("/joint_states", JointState, self.callback) i2c.address(0x05) i2c.writeByte(ctypes.c_uint8(183).value) rospy.sleep(rospy.Duration(0, 5000000)) i2c.writeByte(ctypes.c_uint8(1).value) rospy.sleep(rospy.Duration(0, 5000000)) i2c.address(0x04) i2c.writeByte(ctypes.c_uint8(183).value) rospy.sleep(rospy.Duration(0, 5000000)) i2c.writeByte(ctypes.c_uint8(1).value) rospy.sleep(rospy.Duration(0, 5000000)) i2c.address(0x05) i2c.writeByte(ctypes.c_uint8(183).value) rospy.sleep(rospy.Duration(0, 5000000)) i2c.writeByte(ctypes.c_uint8(1).value) rospy.sleep(rospy.Duration(0, 5000000)) i2c.address(0x06) i2c.writeByte(ctypes.c_uint8(183).value) rospy.sleep(rospy.Duration(0, 5000000)) i2c.writeByte(ctypes.c_uint8(1).value) rospy.sleep(rospy.Duration(0, 5000000)) rospy.spin()
def _read_moves(self): moves = [] node = {} buf = self.read_decrypt_seq(4) flags = 0 commentLen = 0 if self.header["Version"] <= 0xA: if buf[2] & 0xf0: flags |= 0x80 if buf[2] & 0x0f: flags |= 0x40 commentLen = self.read_decrypt_number_seq(4) else: flags = buf[2] flags &= 0xe0 if flags & 0x20: commentLen = self.read_decrypt_number_seq(4) - self.comment_offset src = ctypes.c_uint8(buf[0] - 24 - self.src_offset).value dst = ctypes.c_uint8(buf[1] - 32 - self.dst_offset).value if src < 90 and dst < 90: map = "abcdefghi" src = map[src/10] + str(src%10) dst = map[dst/10] + str(dst%10) else: src = dst = "" node["src"] = src node["dst"] = dst comment = "" if commentLen > 0: comment = self.read_decrypt_string_seq(commentLen) comment = comment.replace("'", "") node["comment"] = comment moves.append(node) if flags & 0x80: nextmoves = self._read_moves() moves += nextmoves if flags & 0x40: altmoves = self._read_moves() node["sub"] = [altmoves, ] if altmoves[0].has_key("sub"): node["sub"] += altmoves[0].pop("sub") return moves
def callback(data): # print data.velocity mi_lista= [a * b for a, b in zip(data.velocity, [x+conversion_vel for x in [0] * len(data.velocity)])] mi_lista = [round(x+90) for x in mi_lista] # RF x.address(0x05) x.writeByte(ctypes.c_uint8(183).value) rospy.sleep(rospy.Duration(0, 5000000)) x.writeByte(ctypes.c_uint8(mi_lista[2]).value) rospy.sleep(rospy.Duration(0, 5000000)) # RR x.address(0x04) x.writeByte(ctypes.c_uint8(183).value) rospy.sleep(rospy.Duration(0, 5000000)) x.writeByte(ctypes.c_uint8(mi_lista[4]).value) rospy.sleep(rospy.Duration(0, 5000000)) # LF x.address(0x07) x.writeByte(ctypes.c_uint8(183).value) rospy.sleep(rospy.Duration(0, 5000000)) x.writeByte(ctypes.c_uint8(mi_lista[1]).value) rospy.sleep(rospy.Duration(0, 5000000)) # LR x.address(0x08) x.writeByte(ctypes.c_uint8(183).value) rospy.sleep(rospy.Duration(0, 5000000)) x.writeByte(ctypes.c_uint8(mi_lista[3]).value) rospy.sleep(rospy.Duration(0, 5000000))
def PayloadEncrypt(self, strBuffer, AppSKey, address, dir, sequenceCounter): rawBuffer = HexToByte(strBuffer) rawKey = HexToByte(AppSKey) addressInt = int(address, 16) enBuffer = (c_uint8 * 64)() self.Crypto.LoRaMacPayloadEncrypt(create_string_buffer(rawBuffer), c_uint8(len(rawBuffer)), create_string_buffer(rawKey), c_uint32(addressInt), c_uint8(dir), c_uint32(sequenceCounter), byref(enBuffer)) return "".join(("%02x" % i) for i in enBuffer[:len(rawBuffer)])
def setWaveform(self, waveform, sample_rate, finite = 0, clock = "ctr0out", rising = True): waveform_len = len(waveform)/self.channels clock_source = "" if len(clock) > 0 and not clock is "OnboardClock": clock_source = "/Dev" + str(self.board_number) + "/" + str(clock) # set the timing for the waveform. sample_mode = DAQmx_Val_ContSamps if finite: sample_mode = DAQmx_Val_FiniteSamps c_rising = ctypes.c_long(DAQmx_Val_Rising) if (not rising): c_rising = ctypes.c_long(DAQmx_Val_Falling) with getLockForBoard(self.board_number): checkStatus(nidaqmx.DAQmxCfgSampClkTiming(self.taskHandle, ctypes.c_char_p(clock_source), ctypes.c_double(sample_rate), c_rising, ctypes.c_long(sample_mode), ctypes.c_ulonglong(waveform_len))) # transfer the waveform data to the DAQ board buffer. data_len = len(waveform) c_samples_written = ctypes.c_int(data_len) c_wave_form_type = ctypes.c_uint8 * data_len self.c_waveform = c_wave_form_type() for i in range(data_len): if (waveform[i] > 0): self.c_waveform[i] = ctypes.c_uint8(1) else: self.c_waveform[i] = ctypes.c_uint8(0) with getLockForBoard(self.board_number): checkStatus(nidaqmx.DAQmxWriteDigitalLines(self.taskHandle, ctypes.c_int(waveform_len), ctypes.c_int(0), ctypes.c_double(10.0), ctypes.c_int(DAQmx_Val_GroupByChannel), ctypes.byref(self.c_waveform), ctypes.byref(c_samples_written), None)) if (c_samples_written.value == waveform_len): return True else: return False
def setSuperKControlEmission(COMPort,state): """ Sets the SuperK emission. """ waitTime = 3 #wait time for emission to switch (can take a few seconds) superKBitCluster = getSuperKStatusBits(COMPort) variaBitCluster = getVariaStatusBits(COMPort) dll.SetSuperKControlEmission(COMPort, c_uint8(state) ) sleep(waitTime) #wait for emission to switch superKBitCluster = getSuperKStatusBits(COMPort) if (superKBitCluster.bit15 == 1): #if superK status bit15 tripped due to interlock, it should have cleared. If it hasn't here, it must be another error so stop. dll.SetSuperKControlEmission(COMPort, c_uint8(0) ) raise SuperKHWError('ERROR (superk.setSuperKControlEmission). System error. Emission state unknown. Check system.')
def keycode_to_string(context, keycode, modifier_state=0): """Converts a keycode to a string. """ LENGTH = 4 keyboard_type, layout_data = context dead_key_state = ctypes.c_uint32() length = ctypes.c_uint8() unicode_string = (ctypes.c_uint16 * LENGTH)() CarbonExtra.UCKeyTranslate(layout_data, keycode, CarbonExtra.kUCKeyActionDisplay, modifier_state, keyboard_type, CarbonExtra.kUCKeyTranslateNoDeadKeysBit, ctypes.byref(dead_key_state), LENGTH, ctypes.byref(length), unicode_string) return u''.join(six.unichr(unicode_string[i]) for i in range(length.value))
def read_word_data(self, addr, cmd): """Read a word (2 bytes) from the specified cmd register of the device. Note that this will interpret data using the endianness of the processor running Python (typically little endian)! """ assert self._device is not None, 'Bus must be opened before operations are made against it!' # Build ctypes values to marshall between ioctl and Python. reg = c_uint8(cmd) result = c_uint16() # Build ioctl request. request = make_i2c_rdwr_data([ (addr, 0, 1, pointer(reg)), # Write cmd register. (addr, I2C_M_RD, 2, cast(pointer(result), POINTER(c_uint8))) # Read word (2 bytes). ]) # Make ioctl call and return result data. ioctl(self._device.fileno(), I2C_RDWR, request) return result.value
def write_read_data(self, byte_to_write, bytes_to_read): # Build ctypes values to marshall between ioctl and Python. reg = ctypes.c_uint8(byte_to_write) result = ctypes.create_string_buffer(bytes_to_read) #From ctypes request = make_i2c_rdwr_data([ (self.i2c_addr, 0, 1, ctypes.pointer(reg)), # Write cmd register. (self.i2c_addr, I2C_M_RD, bytes_to_read, ctypes.cast(result, ctypes.POINTER(ctypes.c_uint8))) # Read data. ]) fcntl.ioctl(self._fd, I2C_RDWR, request) data = bytearray( result.raw ) # Use .raw instead of .value which will stop at a null byte! self.logger.debug( "write_read_data: byte_to_write:%s bytes_to_read:%s => data:%s", byte_to_write, bytes_to_read, data) return data
def generateRawSignature( Message ): # We encode the message if isinstance( Message, str ): Message = base64.b64encode( Message ) elif not isinstance( Message, bytes ): raise Exception("The input must be a string or an array of bytes") # Not sure how to initialize this function as it takes an array of a specific # length. So we provide the arguments and return types. Note that the "+1" to # the length is to include the null character to terminate the string common.GenerateRawSignature.argtypes = ( ctypes.c_char * (1 + len(Message)) ), \ ctypes.c_uint16, \ ( ctypes.c_uint8 * MAX_ECDSA_SIGN_SIZE ), \ ctypes.POINTER( ctypes.c_uint16 ), \ ctypes.c_char_p, \ ctypes.c_uint8 common.GenerateRawSignature.restypes = ctypes.c_int # We prepare the values for retrieving the certificate pMessage = ctypes.create_string_buffer( Message ) uMessageLen = ctypes.c_uint16( len(pMessage) ) # Only SHA256 signatures are supported by the eSIM. So currently, we hardcode # the length of the signature that is sent back. Note that the signature has # two 256-bit values and is ASN.1 encoded. The length should therefore not # exceed 72 bytes. pSignature = ( ctypes.c_uint8 * MAX_ECDSA_SIGN_SIZE )() pu16SignLen = ctypes.pointer( ctypes.c_uint16() ); uLogLevel = ctypes.c_uint8( CPP_LOG_LEVEL ) pPort = MODEM_PORT.encode("utf-8") # We run the command Response = common.GenerateRawSignature( pMessage, uMessageLen, pSignature, pu16SignLen, pPort, uLogLevel ) if Response != ERROR_OK: raise Exception("Error while running function: " + str(Response) ) # We cast the returned value to an array of ints (each int represents a byte) ReturnArray = [] for i in range(pu16SignLen.contents.value): ReturnArray.append( pSignature[i] ) # We convert the array of integers into a base64 string. This requires a few # conversion steps byteCert = np.array( ReturnArray, dtype=np.uint8 ).tobytes() return base64.b64encode( byteCert )
def update_features(self, features, enabled): """ Updates the features bitmask of the image by enabling/disabling a single feature. The feature must support the ability to be dynamically enabled/disabled. :param features: feature bitmask to enable/disable :type features: int :param enabled: whether to enable/disable the feature :type enabled: bool :raises: :class:`InvalidArgument` """ ret = self.librbd.rbd_update_features(self.image, c_uint64(features), c_uint8(enabled)); if ret != 0: raise make_ex(ret, 'error updating features for image %s' % (self.name))
def sha206a_get_dk_useflag_count(dk_avail_count): """ calculates available Derived Key use counts Args: dk_avail_count counts available bit's as 1 (int) Returns: Status Code """ if not isinstance(dk_avail_count, AtcaReference): status = Status.ATCA_BAD_PARAM else: c_dk_avail_count = c_uint8(dk_avail_count.value) status = get_cryptoauthlib().sha206a_get_dk_useflag_count(byref(c_dk_avail_count)) dk_avail_count.value = c_dk_avail_count.value return status
def initiate(): ver = ct.create_string_buffer(8) maxlen = ct.c_uint8(10) res = r11.R11_LibGetVersion(ver, maxlen) if (res==0): print('Software version: %s' % ver.value) else: raise Exception('Libarary not loaded') guid = ct.c_char_p(b"54ED7AC9-CC23-4165-BE32-79016BAFB950") devcount = ct.c_uint16(0) devlist = ct.POINTER(Dev)() res = r11.FDD_DevEnumerateWinUSB(guid, ct.pointer(devlist), ct.byref(devcount)) if (res==0): port = devlist.contents.id.decode() print('Dev port: %s' % port) else: raise Exception('Cannot find the port')
def __init__(self): YAPLCTransaction.__init__(self, 0x6b) dt = datetime.datetime.now() year = dt.year % 100 year = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(year)), 1) mon = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.month)), 1) day = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.day)), 1) hour = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.hour)), 1) minute = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.minute)), 1) second = ctypes.string_at(ctypes.pointer(ctypes.c_uint8(dt.second)), 1) self.Data = year + mon + day + hour + minute + second
def get_array_upper_bound(self, die): for child in die.iter_children(): if child.tag == 'DW_TAG_subrange_type': upper_bound_attr = child.attributes.get( 'DW_AT_upper_bound', None) if upper_bound_attr is None: return None else: if upper_bound_attr.form in ('DW_FORM_data1', 'DW_FORM_data2', 'DW_FORM_data4', 'DW_FORM_data8'): return upper_bound_attr.value elif upper_bound_attr.form == 'DW_FORM_exprloc': loc = upper_bound_attr.value if loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const1u']: return ctypes.c_uint8(loc[1]).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const1s']: return ctypes.c_int8(loc[1]).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const2u']: return ctypes.c_uint16( utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const2s']: return ctypes.c_int16( utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const4u']: return ctypes.c_uint32( utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const4s']: return ctypes.c_int32( utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const8u']: return ctypes.c_uint64( utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_const8s']: return ctypes.c_int64( utils.decode_kbytes(loc[1:], 2)).value elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_constu']: return utils.decode_uleb128(loc[1:]) elif loc[0] == ENUM_DW_FORM_exprloc['DW_OP_consts']: return utils.decode_sleb128(loc[1:]) else: return None else: return None
def crc16Calc(Data, StartElement, Len): """ Calculates 2 Byte CRC """ crc16Table = [0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,\ 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,\ 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,\ 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,\ 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,\ 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,\ 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,\ 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,\ 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,\ 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,\ 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,\ 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,\ 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,\ 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,\ 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,\ 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,\ 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,\ 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,\ 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,\ 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,\ 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,\ 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,\ 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,\ 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,\ 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,\ 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,\ 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,\ 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,\ 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,\ 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,\ 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,\ 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0] crc16 = ctypes.c_uint16(0).value for x in range(StartElement, Len + StartElement): crc16 = (crc16 << 8) ^ ctypes.c_uint16(crc16Table[( (crc16 >> 8) ^ ctypes.c_uint8(Data[x]).value) & 0xff]).value crc16 = ctypes.c_uint16(crc16).value return crc16
def write(self, addr, data): ''' FTI2C write data to address Args: addr: hex, [0~0xFF], Write datas to this address data: list, Datas to be write ''' assert addr >= 0 and addr <= 0xFF assert len(data) > 0 self._ft_4222.open() wr_data = (ctypes.c_ubyte * len(data))() for i in range(len(data)): wr_data[i] = data[i] ftstatus = self._base_lib.FT4222_I2CMaster_Init( self._fthandle, self._kbps) if ftstatus != 0: raise FTI2CException('FT4222_I2CMaster_Init') ftstatus = self._base_lib.FT4222_I2CMaster_Reset(self._fthandle) if ftstatus != 0: raise FTI2CException('FT4222_I2CMaster_Reset') byteswritten = ctypes.c_uint16(0) ftstatus = self._base_lib.FT4222_I2CMaster_Write( self._fthandle, addr, wr_data, len(data), ctypes.byref(byteswritten)) if ftstatus != 0: raise FTI2CException('FT4222_I2CMaster_Write') controllerstatus = ctypes.c_uint8(0) start_time = time.time() while True: ftstatus = self._base_lib.FT4222_I2CMaster_GetStatus( self._fthandle, ctypes.byref(controllerstatus)) if ftstatus != 0: raise FTI2CException('FT4222_I2CMaster_GetStatus') if ((controllerstatus.value) & 0x20) != 0: break if time.time() - start_time > FTI2CDef.TIMEOUT_SEC: raise FTI2CException('Wait idle ready timeout')
def data_8bit(self, level): ''' creates data to send to femo.write inputs level: {'high', 'low'} the option determines if it created data_high or data_low output: an 8 bit ctypes intenger ''' data_dic = getattr(self, ''.join(['data_', level, '_dic'])) data = ''.join(getattr(self, v) for v in data_dic.values()[:: -1]) # print data, 'should be 00000010' # print 'data_8bit:', data return ctypes.c_uint8(int(data, 2))
def stringFromArray(data): ret = '' for i in data: value = ctypes.c_uint8(i).value if value == 0: continue if value <=127: ret += chr(value) else: ret += '\\x' + hex(value)[2:] return ret
def sha206a_check_dk_useflag_validity(is_consumed): """ verifies Derived Key use flags for consumption Args: is_consumed indicates if derived key is available for consumption (Expected AtcaReference) Returns: Status Code """ if not isinstance(is_consumed, AtcaReference): status = Status.ATCA_BAD_PARAM else: c_is_consumed = c_uint8(is_consumed.value) status = get_cryptoauthlib().sha206a_check_dk_useflag_validity(byref(c_is_consumed)) is_consumed.value = c_is_consumed.value return status
def sha206a_verify_device_consumption(is_consumed): """ verifies the device is fully consumed or not based on Parent and Derived Key use flags. Args: is_consumed result of device consumption is returned here (Expected AtcaReference) Returns: Status Code """ if not isinstance(is_consumed, AtcaReference): status = Status.ATCA_BAD_PARAM else: c_is_consumed = c_uint8(is_consumed.value) status = get_cryptoauthlib().sha206a_verify_device_consumption(byref(c_is_consumed)) is_consumed.value = c_is_consumed.value return status
def _get_rule_instance(self, rule_dict): new_rule = FilteringRule() dest_ip = rule_dict.get("dest_ip", 0) if dest_ip != 0: dest_ip = self._translate_ip_string_to_int(dest_ip) new_rule.dip = ctypes.c_uint32(dest_ip) src_ip = rule_dict.get("src_ip", 0) if src_ip != 0: src_ip = self._translate_ip_string_to_int(src_ip) new_rule.sip = ctypes.c_uint32(src_ip) new_rule.dport = ctypes.c_uint16(rule_dict.get("dest_port", 0)) new_rule.sport = ctypes.c_uint16(rule_dict.get("src_port", 0)) new_rule.proto = ctypes.c_uint8(rule_dict.get("proto", 0)) return new_rule
def get_channel_info_(self, handle: int) -> Tuple[int, int]: """ A more convenient version of :meth:`get_channel_info` method (``AlazarGetChannelInfo``). This method hides the fact that the output values in the original function are written to the provided pointers. Args: handle: Handle of the board of interest Returns: Tuple of bits per sample and maximum board memory in samples """ bps = ctypes.c_uint8(0) # bps bits per sample max_s = ctypes.c_uint32(0) # max_s memory size in samples self.get_channel_info(handle, ctypes.byref(max_s), ctypes.byref(bps)) return max_s.value, bps.value
def param_provider_get_bool(reader, name, val): n = name.decode('utf-8') c = reader.current() if n in c: o = c[n] try: int_val = int(o) except TypeError: int_val = int(o[0]) val[0] = ctypes.c_uint8(int_val) log_print('GET scalar [bool] {}: {}'.format(n, bool(val[0]))) return 0 return -1
def param_provider_get_bool_array_item(reader, name, index, val): n = name.decode('utf-8') c = reader.current() if n in c: o = c[n] try: int_val = int(o) except TypeError: int_val = int(o[index]) val[0] = ctypes.c_uint8(int_val) log_print('GET array [bool] ({}) {}: {}'.format( index, n, bool(val[0]))) return 0 return -1
def getLoggedData(self): self.dut.Lib_GMLoggerSIM_GetLoggedData.argtypes = \ [ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8)), ctypes.POINTER(ctypes.c_uint8)] data = ctypes.POINTER(ctypes.c_uint8)() size = ctypes.c_uint8() self.dut.Lib_GMLoggerSIM_GetLoggedData( ctypes.byref(data), ctypes.byref(size)) logged_data = "" for i in range(size.value): logged_data += chr(data[i]) # it is expected that log end with new line, # this should be stripped application return logged_data[:-3]
def _os_call(self): operand = (self.current_instruction & 0x0F00) >> 8 # last nibble logger.debug('Receive OS call %1X', operand) if operand == 0b0000: # Dump current state to stdout uacc = c_uint8(self._acc.value).value sacc = self._acc.value print('-- Current VM State') print('ACC => {0: #05x} | {0: 04d} | {1:#04x} | {1:03d}'.format( sacc, uacc)) print('CI => {0: #05x} | {0: 04d}'.format( self.instruction_counter)) elif operand == 0b1111: # Finish execution self.running = False else: logger.warning('OS call %01X not implemented, skipping', operand)
def cpy(self, arg): """Compare Y Register""" # do in place subtraction, not saving the result result = self.y - arg uint_result = c_uint8(result) # set carry flag if Y >= arg self.p &= ~(const.FLAG_CARRY) self.p |= result > 0 # set zero flag if Y = M self.p &= ~(const.FLAG_ZERO) self.p |= const.FLAG_ZERO if not result else 0b0 # set negative flag if result is negative self.p &= ~(const.FLAG_NEGATIVE) self.p |= const.FLAG_NEGATIVE if uint_result >= 0x80 else 0b0
def read_debug_port_register(self, addr): """ Reads a debug port register. @param int addr: Address to read. @return int: Value read. """ if not is_u8(addr): raise ValueError('The addr parameter must be an unsigned 8-bit value.') addr = ctypes.c_uint8(addr) data = ctypes.c_uint32() result = self._lib.NRFJPROG_read_debug_port_register(addr, ctypes.byref(data)) if result != NrfjprogdllErr.SUCCESS: raise APIError(result) return data.value
def runLwgeom(self, geom, lib, **kwargs): # create a LWGEOM geometry parsing the WKB wkb_in = ctypes.create_string_buffer(geom.asWkb()) wkb_size_in = ctypes.c_int(geom.wkbSize()) LW_PARSER_CHECK_NONE = ctypes.c_char(chr(0)) #define LW_PARSER_CHECK_NONE 0 try: lwgeom_in = lib.lwgeom_from_wkb( wkb_in, wkb_size_in, LW_PARSER_CHECK_NONE ) finally: del wkb_in if not lwgeom_in: SextanteLog.addToLog(SextanteLog.LOG_ERROR, "FAILURE: liblwgeom wasn't able to parse the WKB!") return False # execute the liblwgeom function on the LWGEOM geometry try: lwgeom_out = self.runLwgeomFunc(lwgeom_in, lib=lib, **kwargs) finally: lib.lwgeom_free( lwgeom_in ) del lwgeom_in if not lwgeom_out: return # convert the LWGEOM geometry back to WKB wkb_size_out = ctypes.c_size_t() WKB_ISO = ctypes.c_uint8(1) #define WKB_ISO 0x01 try: wkb_out = lib.lwgeom_to_wkb( lwgeom_out, WKB_ISO, ctypes.byref(wkb_size_out) ) finally: lib.lwgeom_free( lwgeom_out ) del lwgeom_out if not wkb_out or wkb_size_out <= 0: SextanteLog.addToLog(SextanteLog.LOG_ERROR, "FAILURE: liblwgeom wasn't able to convert the geometry back to WKB!") return False # update the QgsGeometry through the WKB wkb_geom = ctypes.string_at(wkb_out, wkb_size_out.value) lib.lwfree( wkb_out ) del wkb_out geom.fromWkb( wkb_geom ) return True
def on_flow_update(self, packet_information, flow): # Is the detection of the application completed? if flow.classifiers[self.name]['detection_completed'] == 0: # It is not, then process the current packet with nDPI library flow.classifiers[self.name][ 'detected_protocol'] = ndpi.ndpi_detection_process_packet( self.mod, flow.classifiers[self.name]['ndpi_flow'], cast(cast(c_char_p(packet_information.content), c_void_p), POINTER(c_uint8)), len(packet_information.content), packet_information.ts, flow.classifiers[self.name]['src_id'], flow.classifiers[self.name]['dst_id']) # Initialize a "valid" variable that will be set as True if the total number of exchanged packets (in both directions) in the flow # is bigger than 10 for TCP or if it is bigger than 16 packets for UDP valid = False # Is the transport protocol TCP? if flow.ip_protocol == 6: # Check if the total quantity of packets (in both directions) is bigger than 10 # and set valid to True if it is the case valid = (flow.src_to_dst_pkts + flow.dst_to_src_pkts ) > self.max_num_tcp_dissected_pkts # It is not TCP, then is the transport protocol UDP? elif flow.ip_protocol == 17: # Check if the total quantity of packets (in both directions) is bigger than 16 # and set valid to True if it is the case valid = (flow.src_to_dst_pkts + flow.dst_to_src_pkts ) > self.max_num_udp_dissected_pkts # Is valid is TRUE or the detected application protocol is different from UNKNOWN if valid or flow.classifiers[ self.name]['detected_protocol'].app_protocol != 0: # Is valid is TRUE or the detected master protocol is different from TLS (Transport Layer Security) if valid or flow.classifiers[ self.name]['detected_protocol'].master_protocol != 91: # The classification process of the packet is completed, set to 1 flow.classifiers[self.name]['detection_completed'] = 1 # Is the detected application protocol UNKOWN (number 0) if flow.classifiers[ self.name]['detected_protocol'].app_protocol == 0: # Stop the detection, the nDPI library could not detect the application protocol flow.classifiers[self.name][ 'detected_protocol'] = ndpi.ndpi_detection_giveup( self.mod, flow.classifiers[self.name]['ndpi_flow'], 1, cast(addressof(c_uint8(0)), POINTER(c_uint8)))
def trackControl(trk, code, out, flags): o = c_uint8(0) i = c_uint8(0) txbuf = [i.value, i.value, i.value, i.value, i.value, i.value, i.value, i.value, i.value, i.value] o = out & 0x07 txbuf[0] = SOM1 txbuf[1] = SOM2 txbuf[2] = 0x0a txbuf[3] = CMD_TRACK_CONTROL txbuf[4] = c_uint8(code).value txbuf[5] = c_uint8(trk).value txbuf[6] = c_uint8(trk >> 8).value txbuf[7] = c_uint8(o).value txbuf[8] = c_uint8(flags).value txbuf[9] = EOM print(txbuf) ser.write(txbuf)
def get_values(idn, ch): """ Gets the current data values on the given device channel. :param idn: Device identifier. :param ch: Channel. :returns: CurrentValues object. """ idn = c.c_int32(idn) ch = c.c_uint8(ch) values = CurrentValues() logging.debug( '[easy-biologic] Getting values of channel {} on device {}.'.format( ch.value, idn.value)) err = BL_GetCurrentValues(idn, ch, c.byref(values)) validate(err) return values
def read_i2c_block_data(self, addr, cmd, length=32): """Perform a read from the specified cmd register of device. Length number of bytes (default of 32) will be read and returned as a bytearray. """ assert self._device is not None, 'Bus must be opened before operations are made against it!' # Build ctypes values to marshall between ioctl and Python. reg = c_uint8(cmd) result = create_string_buffer(length) # Build ioctl request. request = make_i2c_rdwr_data([ (addr, 0, 1, pointer(reg)), # Write cmd register. (addr, I2C_M_RD, length, cast(result, POINTER(c_uint8))) # Read data. ]) # Make ioctl call and return result data. ioctl(self._device.fileno(), I2C_RDWR, request) return bytearray( result.raw ) # Use .raw instead of .value which will stop at a null byte!
def _prepare_args(self, ty, val, stream, retr): if isinstance(ty, types.Array): devary, conv = devicearray.auto_device(val, stream=stream) if conv: retr.append(lambda: devary.copy_to_host(val, stream=stream)) return devary.as_cuda_arg() elif isinstance(ty, types.Integer): return getattr(ctypes, "c_%s" % ty)(val) elif ty == types.float64: return ctypes.c_double(val) elif ty == types.float32: return ctypes.c_float(val) elif ty == types.boolean: return ctypes.c_uint8(int(val)) elif ty == types.complex64: ctx = get_context() size = ctypes.sizeof(Complex64) dmem = ctx.memalloc(size) cval = Complex64(val) driver.host_to_device(dmem, ctypes.addressof(cval), size, stream=stream) return dmem elif ty == types.complex128: ctx = get_context() size = ctypes.sizeof(Complex128) dmem = ctx.memalloc(size) cval = Complex128(val) driver.host_to_device(dmem, ctypes.addressof(cval), size, stream=stream) return dmem else: raise NotImplementedError(ty, val)
def channel_info(idn, ch): """ Returns information on the specified channel. :param idn: The device id. :param ch: The channel. :returns: ChannelInfo structure. """ idn = c.c_int32(idn) ch = c.c_uint8(ch) info = ChannelInfo() logging.debug( '[easy-biologic] Getting info for channel {} on device {}.'.format( ch.value, idn.value)) err = BL_GetChannelInfos(idn, ch, c.byref(info)) validate(err) return info