def _init_xkb_handler(self): XCB_XKB_EVENT_TYPE_EXTENSION_DEVICE_NOTIFY = 2048 affectWhich = ctypes.c_ushort( XCB_XKB_EVENT_TYPE_EXTENSION_DEVICE_NOTIFY ) affectMap = ctypes.c_ushort(0) cookie = self.xcb_xkb.xcb_xkb_select_events_checked( self.conn, use_core_kbd, affectWhich, ctypes.c_ushort(0), affectWhich, affectMap, affectMap, None ) err = self.xcb.xcb_request_check(self.conn, cookie) if err: self.xcb_xkb.free(err) print("Cant initialize event handler") self._exit() self.xcb.xcb_poll_for_event.restype = ctypes.POINTER( xcb_generic_event_t ) self.xcb.xcb_flush(self.conn) self.timeout_id = GObject.timeout_add( POLL_TIMEOUT, self.poll, None )
def calculate(self, string=''): '''Calculate a CRC-CCITT(Kermit) for hexadecimal string and returns a decimal value''' try: if not isinstance(string, str): raise Exception( "Please provide a string as argument for calculation.") if not string: return 0 crcValue = 0x0000 c = '' for d in string: c += d if len(c) == 2: short_c = 0x00ff & c_ushort(int(c, 16)).value tmp = crcValue ^ short_c crcValue = c_ushort( crcValue >> 8).value ^ int( self.crc16kermit_tab[(tmp & 0xff)], 0) c = '' # After processing, the one's complement of # the CRC is calcluated and the two bytes of the CRC are swapped. low_byte = (crcValue & 0xff00) >> 8 high_byte = (crcValue & 0x00ff) << 8 crcValue = low_byte | high_byte return crcValue except Exception as e: print(("EXCEPTION(calculate): {}".format(e)))
def _calculate_crc_ccitt(data): """ All CRC stuff ripped from PyCRC, GPLv3 licensed """ global CRC_CCITT_TABLE if not CRC_CCITT_TABLE: crc_ccitt_table = [] for i in range(0, 256): crc = 0 c = i << 8 for j in range(0, 8): if (crc ^ c) & 0x8000: crc = c_ushort(crc << 1).value ^ 0x1021 else: crc = c_ushort(crc << 1).value c = c_ushort(c << 1).value crc_ccitt_table.append(crc) CRC_CCITT_TABLE = crc_ccitt_table is_string = _is_string(data) crc_value = 0x0000 # XModem version for c in data: d = ord(c) if is_string else c tmp = ((crc_value >> 8) & 0xff) ^ d crc_value = ((crc_value << 8) & 0xff00) ^ CRC_CCITT_TABLE[tmp] return crc_value
def send_mgmt_active_set(self, active_timestamp=None, channel=None, channel_mask=None, extended_panid=None, panid=None, master_key=None, mesh_local=None, network_name=None, binary=None): if active_timestamp == None: active_timestamp = 0 if panid == None: panid = 0 if channel == None: channel = 0 if channel_mask == None: channel_mask = 0 if extended_panid == None: extended_panid = "" if master_key == None: master_key = "" if mesh_local == None: mesh_local = "" if network_name == None: network_name = "" if binary == None: binary = "" if self.Api.otNodeSendActiveSet( self.otNode, ctypes.c_ulonglong(active_timestamp), ctypes.c_ushort(panid), ctypes.c_ushort(channel), ctypes.c_uint(channel_mask), extended_panid.encode('utf-8'), master_key.encode('utf-8'), mesh_local.encode('utf-8'), network_name.encode('utf-8'), binary.encode('utf-8') ) != 0: raise OSError("otNodeSendActiveSet failed!")
def calcCCITT_Kermit(cls, data): if not len(cls.crc16kermit_tab): for i in range(0, 256): crc = c_ushort(i).value for j in range(0, 8): if (crc & 0x0001): crc = c_ushort(crc >> 1).value ^\ cls.crc16Kermit_constant else: crc = c_ushort(crc >> 1).value cls.crc16kermit_tab.append(hex(crc)) crcValue = 0x0000 for c in data: tmp = crcValue ^ c crcValue = c_ushort(crcValue >> 8).value ^\ int(cls.crc16kermit_tab[(tmp & 0x00ff)], 0) # After processing, the one's complement of the CRC is # calcluated and the two bytes of the CRC are swapped. low_byte = (crcValue & 0xff00) >> 8 high_byte = (crcValue & 0x00ff) << 8 crcValue = low_byte | high_byte return crcValue
def send_mgmt_pending_set(self, pending_timestamp=None, active_timestamp=None, delay_timer=None, channel=None, panid=None, master_key=None, mesh_local=None, network_name=None): if pending_timestamp == None: pending_timestamp = 0 if active_timestamp == None: active_timestamp = 0 if delay_timer == None: delay_timer = 0 if panid == None: panid = 0 if channel == None: channel = 0 if master_key == None: master_key = "" if mesh_local == None: mesh_local = "" if network_name == None: network_name = "" if self.Api.otNodeSendPendingSet( self.otNode, ctypes.c_ulonglong(active_timestamp), ctypes.c_ulonglong(pending_timestamp), ctypes.c_uint(delay_timer), ctypes.c_ushort(panid), ctypes.c_ushort(channel), master_key.encode('utf-8'), mesh_local.encode('utf-8'), network_name.encode('utf-8') ) != 0: raise OSError("otNodeSendPendingSet failed!")
def init(resourceName, resetDevice=False, options={}): """Initializes an instrument resourceName - string which identifies the resource to be initialized resetDevice - if True, resets the module after initialization options - options to be used in initialization. If options are given, then this calls Acqrs_initWithOptions, otherwise it calls Acqrs_init. Options can be specified as a string in the form required by the driver, or as a python map, e.g. options={'CAL': False} returns the instrumentID of the initialized instrument. """ instrumentID = c_uint() if options: if isinstance(options, str): optionsString = options else: optionsString = ','.join('%s=%s' % (k, v) for (k, v) in options.items()) call('initWithOptions', c_char_p(resourceName), False, c_ushort(resetDevice), optionsString, byref(instrumentID)) else: call('init', c_char_p(resourceName), False, c_ushort(resetDevice), byref(instrumentID)) return instrumentID.value
def calculate(self, string = ''): try: if not isinstance(string, str): raise Exception("Please provide a string as argument for calculation.") if not string: return 0 crcValue = 0x0000 for idx, c in enumerate(string): short_c = 0x00ff & ord(c) idx_previous = idx - 1 prev_c = 0 if idx_previous == -1 else ord(string[idx_previous]) short_p = ( 0x00ff & prev_c) << 8; if ( crcValue & 0x8000 ): crcValue = c_ushort(crcValue << 1).value ^ self.crc16SICK_constant else: crcValue = c_ushort(crcValue << 1).value crcValue &= 0xffff crcValue ^= ( short_c | short_p ) # After processing, the one's complement of the CRC is calcluated and the # two bytes of the CRC are swapped. low_byte = (crcValue & 0xff00) >> 8 high_byte = (crcValue & 0x00ff) << 8 crcValue = low_byte | high_byte; return crcValue except Exception, e: print "EXCEPTION(calculate): {}".format(e)
def checkPacket(self, data): ''' Parse packet, decode, validate checksum, emit''' # Parse Header (10 Bytes) header = list(struct.unpack('!BHHIB', unhexlify(data[:20]))) # Start Crypto aXOR32 = XOR32(33 + self.XOR32_seed + header[1]) # Alter Vars Against Crypto header[0] ^= self.getByteAsInt(aXOR32.next()) header[2] ^= self.getShortAsInt(aXOR32.next()) header[3] ^= aXOR32.next() header[4] ^= self.getByteAsInt(aXOR32.next()) # Compute TMP Checksum checksumTmp = ctypes.c_ushort(header[2] + header[3] + (header[3] >> 16) + header[4] + header[0]) if header[0] == 255: log.debug("Resetting comBufferSize to %d." % int(header[3])) header[0] = int(header[3]) # Process Payload payloadDec = array.array('B') if len(data) > 20: data = unhexlify(data[20:]) if header[0] > 1384: log.debug("Header longer then possible data! Abort Processing!") else: if len(data) != header[0]: log.debug("Payload Length MisMatch! Data is %d bytes. Header says %d bytes." % (len(data), header[0])) if len(data) < header[0]: log.debug("Less actual data than what header wants. 0 Padding.") diff = header[0] - len(data) data = data + ('\x00' * diff) else: log.debug("More actual data than header expects, trimming") data = data[:header[0]] payload = list(struct.unpack('!%dB' % header[0], data)) for byte in payload: #print "Byte: ", byte byte ^= self.getByteAsInt(aXOR32.next()) #print "Byte Dec: ", byte payloadDec.append(byte) # Process Checksum checksumTmp.value += ctypes.c_ushort(byte).value # Processing Done #print "Header Post:", header #print "CheckSumTmp:", checksumTmp.value #print "Payload:", payloadDec #print "Final Checksums:", checksumTmp.value, header[1] # Test Checksums if checksumTmp.value == header[1]: self.processCommand(header[2], header[3], header[4], payloadDec) else: log.debug("Checksum Mis-match: %s %s!" % (checksumTmp.value, header[1]))
def init_crc16(self): '''The algorithm use tables with precalculated values''' for i in range(0, 256): crc = c_ushort(i).value for j in range(0, 8): if (crc & 0x0001): crc = c_ushort(crc >> 1).value ^ self.crc16_constant else: crc = c_ushort(crc >> 1).value self.crc16_tab.append(hex(crc))
def __init__(self): """ Create pressure sensor communication interface. """ self._lib = ct.CDLL('librpims5x.so.0') self._lib.rpims5x_init() self._p_value = ct.c_ushort() self._t_value = ct.c_ushort()
def __init__(self,code,value): self.buffer_length=_C.c_ushort(4) self.code=_C.c_ushort(code) self.pointer=_C.pointer(value) self.retlen=_C.c_void_p(0) self.buffer_length2=0 self.code2=0 self.pointer2=_C.c_void_p(0) self.retlen2=_C.c_void_p(0)
def __init__(self,code,buflen,string_p,retlen_p): self.buffer_length=_C.c_ushort(buflen) self.code=_C.c_ushort(code) self.pointer=string_p self.retlen=_C.pointer(retlen_p) self.buffer_length2=0 self.code2=0 self.pointer2=_C.c_void_p(0) self.retlen2=_C.c_void_p(0)
def init_crc16dnp(self): """The algorithm use tables with precalculated values""" for i in range(0, 256): crc = c_ushort(i).value for j in range(0, 8): if crc & 0x0001: crc = c_ushort(crc >> 1).value ^ self.crc16dnp_constant else: crc = c_ushort(crc >> 1).value self.crc16dnp_tab.append(hex(crc))
def get_library_info(self): if not self.lib: raise RXPException("scanifc-mt-s dll not loaded") self.lib_major = ctypes.c_ushort() self.lib_minor = ctypes.c_ushort() self.lib_build = ctypes.c_ushort() self._wrap_call(self.lib.scanifc_get_library_version( ctypes.byref(self.lib_major), ctypes.byref(self.lib_minor), ctypes.byref(self.lib_build) ))
def init_crc_ccitt(self): '''The algorithm use tables with precalculated values''' for i in range(0, 256): crc = 0 c = i << 8 for j in range(0, 8): if ((crc ^ c) & 0x8000): crc = c_ushort(crc << 1).value ^ self.crc_ccitt_constant else: crc = c_ushort(crc << 1).value c = c_ushort(c << 1).value # equiv c = c << 1 self.crc_ccitt_tab.append(hex(crc))
def read_calibration_data(self): self.AC1 = c_short(self.read_calibration_slot(0xaa)).value self.AC2 = c_short(self.read_calibration_slot(0xac)).value self.AC3 = c_short(self.read_calibration_slot(0xae)).value self.AC4 = c_ushort(self.read_calibration_slot(0xb0)).value self.AC5 = c_ushort(self.read_calibration_slot(0xb2)).value self.AC6 = c_ushort(self.read_calibration_slot(0xb4)).value self.B1 = c_short(self.read_calibration_slot(0xb6)).value self.B2 = c_short(self.read_calibration_slot(0xb8)).value self.MB = c_short(self.read_calibration_slot(0xba)).value self.MC = c_short(self.read_calibration_slot(0xbc)).value self.MD = c_short(self.read_calibration_slot(0xbe)).value
def calculate(self, string = ''): try: if not isinstance(string, str): raise Exception("Please provide a string as argument for calculation.") if not string: return 0 crcValue = self.starting_value for c in string: tmp = (c_ushort(crcValue >> 8).value) ^ int('{:08b}'.format(ord(c))[::-1], 2) crcValue = (c_ushort(crcValue << 8).value) ^ int(self.crc_ccitt_tab[tmp], 0) return crcValue except Exception, e: print "EXCEPTION(calculate): {}".format(e)
def _getSystemName(self, coordx, coordy, sysNum): """Compute the name from the star system coordinations.""" cx = coordx + sysNum cy = coordy + cx cx = ROL(c_ushort(cx).value, 3) + cy cy = ROL(c_ushort(cy).value, 5) + cx cx = ROL(c_ushort(cx).value, sysNum) cx += ROL(c_ushort(cy).value, 4) name = "" for i in range(3): name += data.NamePart[(cx >> 2) & 31] cx = ROR(c_ushort(cx).value, 5) return name.capitalize()
def init_crc_table(self): """The algorithm uses tables with precalculated values""" for i in range(0, 256): crc = 0 c = i << 8 for j in range(0, 8): if (crc ^ c) & 0x8000: crc = c_ushort(crc << 1).value ^ self.crc_ccitt_constant else: crc = c_ushort(crc << 1).value c = c_ushort(c << 1).value # equivalent of c = c << 1 self.crc_ccitt_table.append(crc)
def write_pattern_line(device, time, r, g, b, pos): time = c_ushort(time) r = c_ubyte(r) g = c_ubyte(g) b = c_ubyte(b) pos = c_ubyte(pos) writePatternLine(device, time, r, g, b, pos)
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 connect(self): databroker = self._databroker if self._conn is None: conn = databroker.create_connection() self._conn = conn eptTCP = dbrksvrtype.TProtocolType.eptTCP.value emtVideo = dbrksvrtype.TMediaType.emtVideo.value emtAudio = dbrksvrtype.TMediaType.emtAudio.value conn_opt = dbrkhelper.TDataBrokerConnectionOptions() conn_opt.pzIPAddr = ctypes.c_char_p(self._camera.url) conn_opt.wHttpPort = ctypes.c_ushort(self._camera.http_port) conn_opt.pzUID = ctypes.c_char_p(self._camera.username) conn_opt.pzPWD = ctypes.c_char_p(self._camera.password) conn_opt.dwProtocolType = eptTCP conn_opt.pzServerType = "auto" conn_opt.dwMediaType = (emtVideo | emtAudio) conn_opt.pfStatus = dbrkhelper.FTDataBrokerStatusCallback(self._update_connection_status) conn_opt.pfAV = dbrkhelper.FTDataBrokerAVCallback(self._put_one_frame) dwFlags = dbrkhelper.TDataBrokerConnOptionFlag.eConOptProtocolAndMediaType.value dwFlags |= dbrkhelper.TDataBrokerConnOptionFlag.eConOptHttpPort.value conn_opt.dwFlags = ctypes.c_ulong(dwFlags) databroker.set_connection_options(conn, conn_opt) else: conn = self._conn return databroker.connect(conn)
def read(self, jobnr): ''' Read points from an rxp file ''' if not self.file: raise RXPException("RXPFile is not open") want = ctypes.c_uint(NTARGS) pxyz32 = (_C_scanifc_xyz32_t * NTARGS)() pattributes = (_C_scanifc_attributes_t * NTARGS)() ptime = (ctypes.c_ulonglong * NTARGS)() got = ctypes.c_uint() eof = ctypes.c_bool() while True: self._wrap_call(self.lib.scanifc_rmsstream_read( self.file, want, ctypes.byref(pxyz32), ctypes.byref(pattributes), ctypes.byref(ptime), ctypes.byref(got), ctypes.byref(eof), ctypes.byref(ctypes.c_ushort(jobnr)) )) self.data = [ptime, pxyz32, pattributes] break
def attach_filter(fd, iface, bpf_filter_string): """Attach a BPF filter to the BPF file descriptor""" # Retrieve the BPF byte code in decimal command = "%s -i %s -ddd -s 1600 '%s'" % (conf.prog.tcpdump, iface, bpf_filter_string) try: f = os.popen(command) except OSError as msg: raise Scapy_Exception("Failed to execute tcpdump: (%s)" % msg) # Convert the byte code to a BPF program structure lines = f.readlines() if lines == []: raise Scapy_Exception("Got an empty BPF filter from tcpdump !") # Allocate BPF instructions size = int(lines[0]) bpf_insn_a = bpf_insn * size bip = bpf_insn_a() # Fill the BPF instruction structures with the byte code lines = lines[1:] for i in range(len(lines)): values = [int(v) for v in lines[i].split()] bip[i].code = c_ushort(values[0]) bip[i].jt = c_ubyte(values[1]) bip[i].jf = c_ubyte(values[2]) bip[i].k = c_uint(values[3]) # Create the BPF program and assign it to the interface bp = bpf_program(size, bip) ret = LIBC.ioctl(c_int(fd), BIOCSETF, cast(pointer(bp), c_char_p)) if ret < 0: raise Scapy_Exception("Can't attach the BPF filter !")
def next_id(self, value): """ Internal representation is a short so that it will overflow. Hopefully we shouldn't ever have 65535 pending responses... """ self._next_id = ctypes.c_ushort(value)
def _get_hi_font_mask(self): mask = ctypes.c_ushort() fcntl.ioctl(self._tty, VT_GETHIFONTMASK, mask) assert mask.value & 0xFF == 0 if mask.value != 0x100: raise NotImplementedError return mask.value >> 8
def writeU16(self, u16): try: self.writeBuffer(str(ctypes.c_ushort(u16).value)) except TypeError: self._logger.error('TXML Protocol: Invalid u16 value %s') % (u16) return -1 return 0
def averagedData(instrumentID, channel, readPar, nbrAcq, calculateMean, timeout): """Perform a series of acquisitions and get the resulting averaged waveform instrumentID - instrument identifier channel - the channel to acquire readPar - AqReadParameters structure describing the read request nbrAcq - the number of acquisitions (averages) to perform calculateMean - boolean indicating whether to divide sumArray by nbrAcq to get averages timeout - acquisition timeout in seconds Returns: dataArray - waveform destination array sumArray - waveform accumulation array dataDesc - waveform descriptor structure (AqDataDescriptor) returned values are for the last acquisition segDescArray - segment descriptor structure (AqSegmentDescriptorAvg) returned values are for the last acquisition """ nbrSegments = readPar.nbrSegments nbrSamples = readPar.nbrSamplesInSeg * nbrSegments dataArray = (c_byte * (nbrSamples + 32))() # is this correct, or should it be c_int? sumArray = (c_int * (nbrSamples))() dataDesc = AqDataDescriptor() segDescArray = (AqSegmentDescriptorAvg * nSegments)() readPar.dataArraySize = ctypes.sizeof(dataArray) readPar.segDescArraySize = ctypes.sizeof(segDescArray) call_D1('averagedData', c_uint(instrumentID), c_int(channel), byref(readPar), c_int(nbrAcq), c_ushort(calculateMean), c_double(timeout), dataArray, sumArray, byref(dataDesc), segDescArray) return (dataArray, sumArray, dataDesc, segDescArray)
def encap_push_pdu(self, pdu_bytes, channel=0, label=[1,2,3,4,5,6], protocol=0x0800): ''' Push a PDU into the Tx packet buffer The contents of the PDU, pdu_bytes, should be a sequence of bytes. ''' if channel < 0 or channel >= self.num_channels: raise LibgseWrapperError('Channel number out of range: {}'.format(channel)) if len(label) != 6: raise LibgseWrapperError('Only 6-byte labels supported: {}'.format(label)) num_bytes = min(len(pdu_bytes), 65536) for n in range(num_bytes): self.c_data[n] = pdu_bytes[n] for n in range(6): self.c_label[n] = label[n] self.c_labeltype = c_ubyte(0) self.c_protocol = c_ushort(protocol) status = self.libgse.gse_create_vfrag_with_data(byref(self.c_pdu_vfrag), num_bytes, gse_max_header_length, gse_max_trailer_length, self.c_data, num_bytes) if status != 0: raise LibgseWrapperError('libgse/gse_create_vfrag_with_data: {}'.format(hex(status))) status = self.libgse.gse_encap_receive_pdu(self.c_pdu_vfrag, self.c_encap_state, self.c_label, self.c_labeltype, self.c_protocol, channel) if status != 0: raise LibgseWrapperError('libgse/gse_encap_receive_pdu: {}'.format(hex(status)))
def GetInput( self, nr ): ''' Get input of camera :param nr: Number of input, starts with 0 :return: 0 or 1 if input is reset or set respectively ''' lockHardware.acquire() try: bit_val = ctypes.c_ushort() # first 16 bits are outputs err = meDLL.cbDBitIn( self.deviceNr, FIRSTPORTA, nr + 16, ctypes.byref( bit_val ) ) if err: meDLL.cbGetErrMsg( err, self.errString ) raise HardwareError( self.errString.value ) finally: lockHardware.release() return bit_val.value
def voltage_monitor(h): voltage_list = [] record_id = c_ushort(0) while (record_id.value != 0xffff): record_id, output_data = NM.ipmi_get_sdr_record(h, record_id.value) if output_data.type == 0x01 and output_data.data[7] == 2: voltage_list.append(output_data) all_voltage_monitor_data = [] if not voltage_list: return all_voltage_monitor_data for per_voltage in voltage_list: per_voltage_data = dict(name="", value="", code=1, desc="") per_voltage_data["name"] = get_sensor_name(per_voltage) value, status = read_sensorvalue_and_sensorstatus( h, per_voltage.data[2]) per_voltage_data["value"] = CustomEvent.get_actual_sensor_value( status, value, per_voltage) if per_voltage_data["value"] == "": continue low_critical = get_lower_cirtical_value(per_voltage) up_critical = get_upper_critical_value(per_voltage) if low_critical != r"N/A" and per_voltage_data[ "value"] <= low_critical: per_voltage_data["code"] = 1 per_voltage_data[ "desc"] = "{0}: at or below low critical, Not ok!" all_voltage_monitor_data.append(per_voltage_data) continue elif up_critical != r"N/A" and per_voltage_data[ "value"] >= up_critical: per_voltage_data["code"] = 1 per_voltage_data[ "desc"] = "{0}: at or over up critical, Not ok!" all_voltage_monitor_data.append(per_voltage_data) continue else: per_voltage_data["code"] = 0 per_voltage_data["desc"] = "ok" all_voltage_monitor_data.append(per_voltage_data) return all_voltage_monitor_data
def cbAIn(BoardNum, Chan, Gain, DataValue=0): """Read A/D input channel Inputs ------ BoardNum Chan Gain DataValue Outputs ------- DataValue """ cDataValue = ctypes.c_ushort(DataValue) CHK(cbw.cbAIn(BoardNum, Chan, Gain, ctypes.byref(cDataValue))) return cDataValue.value
def depth_point_2_world_point(kinect, depth_space_point, depthPoint): """ :param kinect: kinect class :param depth_space_point: _DepthSpacePoint from PyKinectV2 :param depthPoint: depth point as array [x, y] :return: return the camera space point """ # Import here for optimization import numpy as np import ctypes depth_point_data_type = depth_space_point * np.int(1) depth_point = ctypes.cast(depth_point_data_type(), ctypes.POINTER(depth_space_point)) depth_point.contents.x = depthPoint[0] depth_point.contents.y = depthPoint[1] world_point = kinect._mapper.MapDepthPointToCameraSpace( depth_point.contents, ctypes.c_ushort(512 * 424)) return [world_point.x, world_point.y, world_point.z] # meters
def createisosurfacemesh(grid, step, offset, isolevel): """ This function creates an isosurface from voxel data using the marching cubes algorithm. Returns a mesh. **Parameters:** `grid` : 3D numpy array containing the voxel data `step` : voxel sizes in each direction `offset` : coordinate origin in each direction `isolevel` : isovalue at which the surface will be created **Raises:** `gr3.GR3_Error.GR3_ERROR_EXPORT`: Raises GR3_Exception +----------------------+-------------------------------+ | GR3_ERROR_NONE | on success | +----------------------+-------------------------------+ | GR3_ERROR_OPENGL_ERR | if an OpenGL error occured | +----------------------+-------------------------------+ | GR3_ERROR_OUT_OF_MEM | if a memory allocation failed | +----------------------+-------------------------------+ """ _mesh = c_uint(0) data = grid.ctypes.data_as(POINTER(c_ushort)) isolevel = c_ushort(isolevel) dim_x, dim_y, dim_z = map(c_uint, grid.shape) stride_x, stride_y, stride_z = map(lambda x: c_uint(x / grid.itemsize), grid.strides) step_x, step_y, step_z = map(c_double, step) offset_x, offset_y, offset_z = map(c_double, offset) err = _gr3.gr3_createisosurfacemesh(byref(_mesh), data, isolevel, dim_x, dim_y, dim_z, stride_x, stride_y, stride_z, step_x, step_y, step_z, offset_x, offset_y, offset_z) if err: raise GR3_Exception(err) return _mesh
def calculate(self, input_data=None): try: is_string = isinstance(input_data, str) is_bytes = isinstance(input_data, bytes) if not is_string and not is_bytes: raise Exception("Please provide a string or a byte sequence " "as argument for calculation.") crcValue = 0x0000 if not self.mdflag else 0xffff for c in input_data: d = ord(c) if is_string else c tmp = crcValue ^ d rotated = c_ushort(crcValue >> 8).value crcValue = rotated ^ int(self.crc16_tab[(tmp & 0x00ff)], 0) return crcValue except Exception as e: print("EXCEPTION(calculate): {}".format(e))
def get_bpf_pointer(tcpdump_lines): """Create a BPF Pointer for TCPDump filter""" # Allocate BPF instructions size = int(tcpdump_lines[0]) bpf_insn_a = bpf_insn * size bip = bpf_insn_a() # Fill the BPF instruction structures with the byte code tcpdump_lines = tcpdump_lines[1:] i = 0 for line in tcpdump_lines: values = [int(v) for v in line.split()] bip[i].code = c_ushort(values[0]) bip[i].jt = c_ubyte(values[1]) bip[i].jf = c_ubyte(values[2]) bip[i].k = c_uint(values[3]) i += 1 # Create the BPF program return bpf_program(size, bip)
def rename_regkey(self, skey, ssubkey, dsubkey): res_handle = HANDLE() options = DWORD(0) res = RegOpenKeyExW(skey, ssubkey, options, KEY_ALL_ACCESS, byref(res_handle)) if not res: bsize = c_ushort(len(dsubkey) * 2) us = UNICODE_STRING() us.Buffer = c_wchar_p(dsubkey) us.Length = bsize us.MaximumLength = bsize res = NtRenameKey(res_handle, pointer(us)) if res: self.log.error('Could not rename %r', ssubkey) else: self.log.info('Renamed %r to %r', ssubkey, dsubkey) if res_handle: RegCloseKey(res_handle)
def cbDBitIn(BoardNum, PortType, BitNum, BitValue): """Read state of a single digital input bit. Inputs ------ BoardNum PortType BitNum BitValue Outputs ------- BitValue """ BitValue = ctypes.c_ushort(BitValue) CHK(cbw.cbDBitIn(BoardNum, PortType, BitNum, byref(BitValue))) return BitValue.value
def _handleEvtInvalidEvtData(user_data, user_data_remaining): """ In this instance, the amount of data we are told to parse exceeds the amount of data that is left in the user data appended to the structure. As viewed in Microsoft Message Analyzer, this appears to be commonly referred to as a fragment. In this case, we simply copy the data to a new buffer, add a NULL terminating character on to the end and call TdhFormatProperty again. :param user_data: A pointer to the user data for the specified segment :param user_data_remaining: The amount of data that is actually left :return: A tuple of the amount consumed and the data itself """ # Instantiate a buffer with enough space for everything plus the NULL terminating character. buf = (ct.c_char * (user_data_remaining + ct.sizeof(ct.c_wchar)))() # Move the data to the new buffer and NULL terminate it. ct.memmove(buf, user_data, user_data_remaining) user_data_consumed = ct.c_ushort(user_data_remaining) return user_data_consumed, buf
def crc16(datos, offset, length): crctab16 = ( 0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF, 0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7, 0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E, 0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876, 0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD, 0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5, 0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C, 0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974, 0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB, 0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3, 0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A, 0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72, 0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9, 0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1, 0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738, 0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70, 0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7, 0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF, 0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036, 0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E, 0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5, 0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD, 0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134, 0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C, 0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3, 0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB, 0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232, 0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A, 0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1, 0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9, 0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330, 0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78, ) fcs = 0xFFFF i = offset while i < length + offset: fcs = ((fcs >> 8) ^ crctab16[(fcs ^ datos[i]) & 0xFF]) i += 1 return ctypes.c_ushort(~fcs).value
def read_configurations(self, print_configuration=True): """read system and sensor configuration from device""" #system configuration sysconf = api.SYSTEM_CONFIGURATION() psys_conf = ctypes.pointer(sysconf) # report SystemConfiguration error_code = api.GetBIRDSystemConfiguration(psys_conf) if error_code != 0: self._error_handler(error_code) self.system_configuration = sysconf report_rate = 0 # TODO report rate is not read out yet #report_rate = ctypes.c_ubyte() #print report_rate #error_code = api.GetSystemParameter(api.SystemParameterType.REPORT_RATE, # ctypes.pointer(report_rate), 2) #if error_code != 0: # self._error_handler(error_code) #print report_rate # read attached sensors config sensor_conf = api.SENSOR_CONFIGURATION() psensor_conf = ctypes.pointer(sensor_conf) attached_sensors = [] for cnt in range(self.system_configuration.numberSensors): error_code = api.GetSensorConfiguration(ctypes.c_ushort(cnt), psensor_conf) if error_code != 0: self._error_handler(error_code) elif sensor_conf.attached: attached_sensors.append(cnt + 1) self.attached_sensors = attached_sensors if print_configuration: print TrakSTARInterface.configuration_text( self.attached_sensors, sysconf.measurementRate, sysconf.maximumRange, bool(sysconf.metric), sysconf.powerLineFrequency, report_rate)
def depth_points_2_world_points(kinect, depth_space_point, depth_points): """ :param kinect: kinect class :param depth_space_point: _DepthSpacePoint :param depth_points: depth points as array [[x, y], [x, y], [x, y].... [x, y]] :return: return camera space points """ import ctypes import numpy as np depth2world_point_type = depth_space_point * np.int(1) depth2world_point = ctypes.cast(depth2world_point_type(), ctypes.POINTER(depth_space_point)) camera_points = np.ndarray(shape=(len(depth_points), 3), dtype=float) for i, point in enumerate(depth_points): depth2world_point.contents.x = point[0] depth2world_point.contents.y = point[1] world_point = kinect._mapper.MapDepthPointToCameraSpace( depth2world_point.contents, ctypes.c_ushort(512 * 424)) camera_points[i] = [world_point.x, world_point.y, world_point.z] return camera_points # meters
def __decode_method(self, dex, offset, methods): for _ in range(methods): _, size = self.__get_uleb128(dex, offset) offset += size _, size = self.__get_uleb128(dex, offset) offset += size code_offset, size = self.__get_uleb128(dex, offset) offset += size if code_offset != 0: current_offset = code_offset code_items = self.__get_code_item(dex, current_offset) current_offset += 16 bytecode_size = ctypes.c_ushort(code_items["insns_size"] * 2).value bytecode_offset = current_offset opcodes = self.__bytecode(dex, bytecode_offset, bytecode_size) self.method_opcode_sequence_list.append(opcodes) return offset
def setFlowControl(self, FlowControl=None, XOn=None, XOff=None): """Set flow control: one of None, RTS_CTS (Hardware), DTR_DSR, or XON_XOFF (Software), and xon and xoff is flow control is XON_XOFF""" if FlowControl is None: FlowControl = self._info.FlowControl if XOn is None: XOn = self._info.XOn if XOff is None: XOff = self._info.XOff if (FlowControl == 'None'): u16 = 0x0000 elif (FlowControl == 'RTS_CTS') or (FlowControl == 'Hardware'): u16 = 0x0100 elif (FlowControl == 'DTR_DSR'): u16 = 0x0200 elif (FlowControl == 'XON_XOFF') or (FlowControl == 'Software'): u16 = 0x0400 else: raise ValueError( 'Valid flow control is None, RTS_CTS, DTR_DSR, or XON_XOFF.') call_ft(dll.FT_SetFlowControl, self.handle, c.c_ushort(u16), UCHAR(XOn), UCHAR(XOff)) self._info.FlowControl = FlowControl self._info.XOn = XOn self._info.XOff = XOff
def rename_regkey(skey, ssubkey, dsubkey): """Rename an entire tree of values in the registry. Function by Thorsten Sick.""" res_handle = HANDLE() options = DWORD(0) res = RegOpenKeyExW(skey, ssubkey, options, KEY_ALL_ACCESS, byref(res_handle)) if not res: bsize = c_ushort(len(dsubkey) * 2) us = UNICODE_STRING() us.Buffer = c_wchar_p(dsubkey) us.Length = bsize us.MaximumLength = bsize res = NtRenameKey(res_handle, pointer(us)) if res: log.warning("Error renaming %s\\%s to %s (0x%x)", skey, ssubkey, dsubkey, res % 2**32) if res_handle: RegCloseKey(res_handle)
def uncompress(self): ''' fi.uncompress() -> None Uncompress a file or directory on a volume whose file system supports per-file and per-directory compression. This method is win32 only. ''' try: import win32file import ctypes except: raise NotSupportedException("this method is win32 only") if not os.path.exists(self.original_path): raise FileNotFoundException("'%s' not found" % self.original_path) if self.is_read_only: raise UnauthorizedAccessException( "'%s' is readonly." % self.original_path) hFile = win32file.CreateFile(self.full_path, win32file.GENERIC_READ | win32file.FILE_GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_BACKUP_SEMANTICS, 0) win32file.DeviceIoControl(hFile, 0x9c040, ctypes.c_ushort(0), 0) win32file.CloseHandle(hFile)
def cbFromEngUnits(BoardNum, Range, EngUnits, DataVal): """Convert a voltage or current to an A/D count value Inputs ------ BoardNum Range EngUnits DataVal Outputs ------- DataVal """ DataVal = ctypes.c_ushort(DataVal) EngUnits = ctypes.c_float(EngUnits) CHK(cbw.cbFromEngUnits(BoardNum, Range, EngUnits, byref(DataVal))) return DataVal.value
def cows_unstuff(array): """ Performs the COWS unstuffing on an input. Args: array: The input to unstuff. The first word will be assumed to be the overhead. """ padded = _pad_array(array) # Make a single forward pass to replace all the zeroes. i = 0 while i < len(array): move_forward = _get_word(array, i) # Set the zero. _set_word(array, i, ctypes.c_ushort(0)) # Move to the next zero. i += 2 * move_forward.value if padded: # Remove the padding. _unpad_array(array)
def parse_value(self, nondet, parsed): if "pointer" in nondet: return None # FIXME pointer models try: if "float" in nondet: val = float(parsed) return ctypes.c_float(val) if "double" in nondet: val = float(parsed) return ctypes.c_double(val) except ValueError: return None try: # integer models: parsed = parsed.lstrip("#x") val = int(parsed, 16) bw = val.bit_length() if "uint" in nondet and bw <= 32: return ctypes.c_uint(val) if "unsigned" in nondet and bw <= 32: return ctypes.c_uint(val) if "int" in nondet and bw <= 32: return ctypes.c_int(val) if "bool" in nondet and bw <= 8: return ctypes.c_bool(val) if "char" in nondet and bw <= 8: return ctypes.c_byte(val) if "ushort" in nondet and bw <= 16: return ctypes.c_ushort(val) if "short" in nondet and bw <= 16: return ctypes.c_short(val) if "ulong" in nondet and bw <= 64: return ctypes.c_ulong(val) if "long" in nondet and bw <= 64: return ctypes.c_long(val) except ValueError: return None return None
def _build_ds_vars(self): ##Populate the DS Vars ds_vars = [] #Create our ctypes to avoid memory hog _size = ctypes.c_short() _type = ctypes.c_short() _units = ctypes.create_string_buffer(20) _desc = ctypes.create_string_buffer(50) for d in self.datasetList: temp_ds_vars = [] for x in np.arange(self.datasetVarsCount + 1): _datas = ctypes.c_ushort(d) CFS64.GetVarDesc(self._fileHandle, ctypes.c_short(x), ctypes.c_short(1), ctypes.byref(_size), ctypes.byref(_type), _units, _desc) if _type.value != 7: _var = dataVarTypes[_type.value][1]() code = CFS64.GetVarVal(self._fileHandle, ctypes.c_short(x), ctypes.c_short(1), ctypes.byref(_datas), ctypes.byref(_var)) var_val = _var else: _var = dataVarTypes[_type.value][1](_size.value) code = CFS64.GetVarVal(self._fileHandle, ctypes.c_short(x), ctypes.c_short(1), ctypes.byref(_datas), _var) var_val = _var.value.decode() dict = { "desc": _desc.value.decode(), "size": _size.value, "units": _units.value.decode(), "type": dataVarTypes[_type.value][0], "value": var_val } temp_ds_vars.append(dict) ds_vars.append(temp_ds_vars) return ds_vars
def join_lockspace(name): """Join DLM lockspace. Affects current node only. Args: name: (str) lockspace name Raises: DLMErrno [EINVAL]: 'name' is longer than the supported length (currently 64 characters) """ handle = _LIBDLM_LT.dlm_open_lockspace(c_char_p(name)) if handle == 0: handle = _LIBDLM_LT.dlm_create_lockspace(c_char_p(name), c_ushort(0o600)) if handle == 0: raise DLMErrno() _LIBDLM_LT.dlm_close_lockspace(handle)
def setConverter(self, newConfig=None): """Initialize a converter to the specified values. :param newConfig: type ConverterSettings """ logger.debug(util.funcName('begin')) if not newConfig: # Useful for multiple converter objects with different settings. newConfig = self.config self.loadLibrary() if not self.funcIsEcInstalled(): raise exceptions.FileAccessError( "EncConverters does not seem to be installed properly.") c_convName = getStringParam(newConfig.convName) if c_convName is None: raise exceptions.LogicError("No converter was specified.") c_forward = ctypes.c_bool(newConfig.forward) c_normForm = ctypes.c_ushort(newConfig.normForm) logger.debug("calling funcInitConverter with %r", newConfig) status = self.funcInitConverter(c_convName, c_forward, c_normForm) verifyStatusOk(status) self.config = newConfig logger.debug(util.funcName('end'))
def getPointCloud(self): while True: if self.kinect.has_new_depth_frame(): dframe = self.kinect.get_last_depth_frame() dwidth = self.kinect.depth_frame_desc.Width dheight = self.kinect.depth_frame_desc.Height pcd = [] for i in range(dheight): for j in range(dwidth): depth = dframe[i * dwidth + j] if depth > 0: point3d = self.kinect.mapper( ).MapDepthPointToCameraSpace( PyKinectV2._DepthSpacePoint( ctypes.c_float(j), ctypes.c_float(i)), ctypes.c_ushort(depth)) # pcd.append((point3d.x*1000.0, point3d.y*1000.0, point3d.z*1000.0)) pcd.append((point3d.x, point3d.y, point3d.z)) break return pcd
def get_address_family(fd): log.msg('Resolving address family of FD %d' % fd) fd_ = ctypes.c_int(fd) addr = ctypes.c_ushort(0) len_ = ctypes.c_int(ctypes.sizeof(addr)) ctypes.set_errno(0) res = getsockname(fd_, ctypes.byref(addr), ctypes.byref(len_)) if res != 0: e = ctypes.get_errno() raise OSError(e, os.strerror(e)) af = addr.value if af in af_map: log.msg('Found address family of FD %d: %s' % (fd, af_map[af])) else: log.msg('Unknown address family of FD %d: %d' % (fd, af)) return af
def __getXYZForPixel(self, dframe, px): """ Convert a depth frame pixel to a 3D point :param dframe: depthframe from pykinectv2 :param px: 1-by-2 list :return: 1-by-3 list [x, y, z] or None author: weibo date: 20180110 """ u, v = int(px[0]), int(px[1]) z3d = dframe[v * self.__depth_width + u] if z3d <= 0: return None point3d = self._mapper.MapDepthPointToCameraSpace( PyKinectV2._DepthSpacePoint(ctypes.c_float(u), ctypes.c_float(v)), ctypes.c_ushort(z3d)) return [point3d.x * 1000.0, point3d.y * 1000.0, point3d.z * 1000.0]
def write_styled(self, text: str, style: Style) -> None: """Write styled text to the terminal. Args: text (str): The text to write style (Style): The style of the text """ color = style.color bgcolor = style.bgcolor if style.reverse: color, bgcolor = bgcolor, color if color: fore = color.downgrade(ColorSystem.WINDOWS).number fore = fore if fore is not None else 7 # Default to ANSI 7: White if style.bold: fore = fore | self.BRIGHT_BIT if style.dim: fore = fore & ~self.BRIGHT_BIT fore = self.ANSI_TO_WINDOWS[fore] else: fore = self._default_fore if bgcolor: back = bgcolor.downgrade(ColorSystem.WINDOWS).number back = back if back is not None else 0 # Default to ANSI 0: Black back = self.ANSI_TO_WINDOWS[back] else: back = self._default_back assert fore is not None assert back is not None SetConsoleTextAttribute( self._handle, attributes=ctypes.c_ushort(fore | (back << 4)) ) self.write_text(text) SetConsoleTextAttribute(self._handle, attributes=self._default_text)
def set_line_control(self, word_length, parity, stop_bits): """ Adjusts the line control settings: word length, stop bits, and parity. Refer to the device data sheet for valid line control settings. """ WORD_LENGTH_OPTIONS = {5: 0x0500, 6: 0x0600, 7: 0x0700, 8: 0x0800} PARITY_OPTIONS = { 'N': 0x0000, 'O': 0x0010, 'E': 0x0020, 'M': 0x0030, 'S': 0x0040 } STOP_BITS_OPTIONS = {'1': 0x0000, '1.5': 0x0001, '2': 0x0002} line_control = STOP_BITS_OPTIONS[stop_bits] | \ PARITY_OPTIONS[parity] | \ WORD_LENGTH_OPTIONS[word_length] self._dll.SI_SetLineControl(self._handle, ctypes.c_ushort(line_control))
def open_siu(): xfs_version_open = WFSVERSION() sp_version = WFSVERSION() hService = ctypes.c_ushort() sensores = wintypes.LPSTR("Sensores".encode('utf-8')) BRXFSTEST = wintypes.LPSTR("BRXFSTEST".encode('utf-8')) WFS_DEFAULT_HAPP = ctypes.c_int(0) traceLevel = wintypes.DWORD(0) timeout = wintypes.DWORD(5000) versionOpen = wintypes.DWORD(0x00030303) hResult = lib_msxfs.WFSOpen(sensores, WFS_DEFAULT_HAPP, BRXFSTEST, traceLevel, timeout, versionOpen, ctypes.byref(xfs_version_open), ctypes.byref(sp_version), ctypes.byref(hService)) ShwWFSOpenResult(hResult, hService, xfs_version_open, sp_version) lib_msxfs.WFSClose(hService) return hResult
def shm_open(name, mode, flags=stat.S_IRUSR | stat.S_IWUSR, initial_size=None): """ mode: os.O_RDWR | os.O_CREAT | os.O_EXCL to create a new block mode: os.O_RDWR to open an existing block """ print(name) if isinstance(name, bytes): name = ctypes.create_string_buffer(name) elif isinstance(name, unicode): name = ctypes.create_unicode_buffer(name) else: raise TypeError("`name` must be `bytes` or `unicode`") result = _shm_open(name, ctypes.c_int(mode), ctypes.c_ushort(flags)) if result == -1: raise RuntimeError(os.strerror(ctypes.get_errno())) if initial_size: print("TRUNCATING TO:", initial_size) os.ftruncate(result, initial_size) return result