Exemple #1
0
    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 word_cnt(self, CommandWord):
     if type(CommandWord) is int:
         return Packet.IrigDataDll.i1553WordCnt(ctypes.byref(ctypes.c_uint16(CommandWord)))
     elif type(CommandWord) is CmdWord:
         return Packet.IrigDataDll.i1553WordCnt(ctypes.byref(ctypes.c_uint16(CommandWord.Value)))
     else:
         return None
Exemple #3
0
 def _get_exposure_time(self):
     dwDelay = C.c_uint32(0)
     wTimeBaseDelay = C.c_uint16(0)
     dwExposure = C.c_uint32(0)
     wTimeBaseExposure = C.c_uint16(1)
     dll.get_delay_exposure_time(
         self.camera_handle,
         dwDelay,
         dwExposure,
         wTimeBaseDelay,
         wTimeBaseExposure)
     time_base_mode_names = {0: "nanoseconds",
                             1: "microseconds",
                             2: "milliseconds"}
     if self.verbose:
         print(" Exposure:", dwExposure.value,
               time_base_mode_names[wTimeBaseExposure.value])
         print(" Delay:", dwDelay.value,
               time_base_mode_names[wTimeBaseDelay.value])
     """
     exposure is returned in microseconds
     """
     self.exposure_time = (dwExposure.value *
                           10.**(3*wTimeBaseExposure.value - 3))
     self.delay_time = dwDelay.value
     return self.exposure_time        
Exemple #4
0
def setVariaControls(COMPort, SWPFilterAngstrom, LWPFilterAngstrom):
    variaBitCluster = getVariaStatusBits(COMPort)
    #superKBitCluster = getSuperKStatusBits(COMPort)
    #if (superKBitCluster.bit0 == 0 or superKBitCluster.bit0 == 1 ): #require emission to be OFF (this needs discussing, I think it's ok to leave o.)
    if (variaBitCluster.bit15 == 0): #require no error (bit15 'general' error bit),
        if (SWPFilterAngstrom > LWPFilterAngstrom): #require high > low wavelength
            if ((SWPFilterAngstrom - LWPFilterAngstrom) >= 100 and (SWPFilterAngstrom - LWPFilterAngstrom) <= 1000): # check wavelength difference is >10nm and <100nm (min and max bandwidth spec'd by manufacturer)
                if (SWPFilterAngstrom <= 8400 and LWPFilterAngstrom >= 4000):
                    dll.SetVariaControls(COMPort, c_uint16(0), c_uint16(SWPFilterAngstrom), c_uint16(LWPFilterAngstrom))
                    variaBitCluster = getVariaStatusBits(COMPort)
                    
                    #now test to see if filters are moving. 30sec is about the time for the largest possible move (give a bit longer)
                    #function keeps running until they have stopped moving (blocking other functions until so)
                    for x in range(71):
                        if (variaBitCluster.bit12 == 1 or variaBitCluster.bit13 == 1 or variaBitCluster.bit14 == 1): #check all filter movement sensors
                            sleep(0.5)
                            variaBitCluster = getVariaStatusBits(COMPort)
                        if (variaBitCluster.bit12 == 0 and variaBitCluster.bit13 == 0 and variaBitCluster.bit14 == 0):
                            break
                        if (x>=70):
                            raise SuperKLogicError( 'ERROR (superk.setVariaControls): Filters have not stopped moving after a long time. Check system.')
                else:
                    raise SuperKLogicError( 'ERROR (superk.setVariaControls): Cannot set to specified values. Minimum LWP wavelength is 400nm. Maximum SWP wavelength is 840nm (with 10nm <= BW <= 100nm).')
            else:
                raise SuperKLogicError( 'ERROR (superk.setVariaControls): Minimum bandwidth is 10nm. Maximum bandwidth is 100nm. SP & LP filters must differ by at least 10nm and no more than 100nm.')
        else:
            raise SuperKLogicError( 'ERROR (superk.setVariaControls): SWP filter value must be larger than LWP filter value')
    else:
        raise SuperKLogicError( 'ERROR (superk.setVariaControls): Setting Varia Filters: ERROR present. Filters not set. Check system.')
Exemple #5
0
    def config_i2c(self, size=None, address=0, clock_rate=100, timeout=2000):
        """
        Set the ni845x I2C configuration.
        
        Parameters
        ----------
            size : Configuration address size (default 7Bit).
            address : Configuration address (default 0).
            clock_rate : Configuration clock rate in kilohertz (default 100).

        Returns
        -------
            None
        """
        if size is None:
            size = self.kNi845xI2cAddress7Bit
        size = ctypes.c_int32(size)
        address = ctypes.c_uint16(address)
        clock_rate = ctypes.c_uint16(clock_rate)
        timeout = ctypes.c_uint32(timeout)
        #
        # create configuration reference
        #
        self.i2c_handle = ctypes.c_int32()
        errChk(ni845x_dll.ni845xI2cConfigurationOpen(ctypes.byref(self.i2c_handle)))
        
        #
        # configure configuration properties
        #
        errChk(ni845x_dll.ni845xI2cConfigurationSetAddressSize(self.i2c_handle, size))
        errChk(ni845x_dll.ni845xI2cConfigurationSetAddress(self.i2c_handle, address))
        errChk(ni845x_dll.ni845xI2cConfigurationSetClockRate(self.i2c_handle, clock_rate))
        errChk(ni845x_dll.ni845xSetTimeout(self.dev_handle, timeout))
Exemple #6
0
    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 test_ctypes_segmented(n):
    while n > 65536:
        for i in range(65536):
            s = ctypes.c_uint16(i)
        n -= 65536
    for i in range(n):
        s = ctypes.c_uint16(i)
Exemple #8
0
    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())
Exemple #9
0
    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)
Exemple #10
0
	def __init__(self, vendor, product, version, name, keys, axes, rels, keyboard=False, rumble=False):
		self._lib = None
		self._k = keys
		self.name = name
		if not axes or len(axes) == 0:
			self._a, self._amin, self._amax, self._afuzz, self._aflat = [[]] * 5
		else:
			self._a, self._amin, self._amax, self._afuzz, self._aflat = zip(*axes)

		self._r = rels
		
		self._lib = find_library("libuinput")
		self._ff_events = None
		if rumble:
			self._ff_events = (POINTER(FeedbackEvent) * MAX_FEEDBACK_EFFECTS)()
			for i in xrange(MAX_FEEDBACK_EFFECTS):
				self._ff_events[i].contents = FeedbackEvent()
		
		try:
			if self._lib.uinput_module_version() != UNPUT_MODULE_VERSION:
				raise Exception()
		except:
			import sys
			print >>sys.stderr, "Invalid native module version. Please, recompile 'libuinput.so'"
			print >>sys.stderr, "If you are running sc-controller from source, you can do this by removing 'build' directory"
			print >>sys.stderr, "and runinng 'python setup.py build' or 'run.sh' script"
			raise Exception("Invalid native module version")
		
		c_k		= (ctypes.c_uint16 * len(self._k))(*self._k)
		c_a		= (ctypes.c_uint16 * len(self._a))(*self._a)
		c_amin	 = (ctypes.c_int32  * len(self._amin ))(*self._amin )
		c_amax	 = (ctypes.c_int32  * len(self._amax ))(*self._amax )
		c_afuzz	= (ctypes.c_int32  * len(self._afuzz))(*self._afuzz)
		c_aflat	= (ctypes.c_int32  * len(self._aflat))(*self._aflat)
		c_r		= (ctypes.c_uint16 * len(self._r))(*self._r)
		c_vendor   = ctypes.c_uint16(vendor)
		c_product  = ctypes.c_uint16(product)
		c_version  = ctypes.c_uint16(version)
		c_keyboard = ctypes.c_int(keyboard)
		c_rumble = ctypes.c_int(MAX_FEEDBACK_EFFECTS if rumble else 0)
		c_name = ctypes.c_char_p(name)
		
		self._fd = self._lib.uinput_init(ctypes.c_int(len(self._k)),
										 c_k,
										 ctypes.c_int(len(self._a)),
										 c_a,
										 c_amin,
										 c_amax,
										 c_afuzz,
										 c_aflat,
										 ctypes.c_int(len(self._r)),
										 c_r,
										 c_keyboard,
										 c_vendor,
										 c_product,
										 c_version,
										 c_rumble,
										 c_name)
		if self._fd < 0:
			raise CannotCreateUInputException("Failed to create uinput device. Error code: %s" % (self._fd,))
    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
Exemple #12
0
def crc_xmodem_update(crc, data):
    crc = ctypes.c_uint16(crc.value ^ data.value << 8)
    for i in range(0, 8):
        if crc.value & 0x8000:
            crc = ctypes.c_uint16((crc.value << 1) ^ 0x1021)
        else:
            crc = ctypes.c_uint16(crc.value << 1)
    return crc
Exemple #13
0
def and_or(line):
    left = c_uint16(eval(line[0]))
    right = c_uint16(eval(line[2]))
    if line[1] == 'AND':
      n = left.value & right.value
    else:
      n = left.value | right.value
    assign([n, None, line[-1]])
Exemple #14
0
 def rect(self, i):
     left = c_uint16()
     right = c_uint16()
     top = c_uint16()
     bottom = c_uint16()
     self._rect(self, i, ctypes.byref(left), ctypes.byref(right),
                ctypes.byref(top), ctypes.byref(bottom))
     return (left.value, right.value, top.value, bottom.value)
Exemple #15
0
def getVariaControls(COMPort):
    """
    undocumented
    """
    NDFilterSetpointPercentx10 = c_uint16(0) #not used
    SWPFilterAngstrom = c_uint16(0)
    LWPFilterAngstrom = c_uint16(0)
    dll.GetVariaControls(COMPort, byref(NDFilterSetpointPercentx10), byref(SWPFilterAngstrom), byref(LWPFilterAngstrom))
    return SWPFilterAngstrom.value, LWPFilterAngstrom.value
Exemple #16
0
def evaluate(ident):
  print 'evaluating ident', ident
  if ident.isdigit():
    return c_uint16(int(ident))
  elif ident in cache:
    return  c_uint16(int(cache[ident]))
  elif ident in wires: 
    return wires[ident]
  else:
    return c_uint16(int(ident))
Exemple #17
0
 def fromCLSID(cls, clsid):
     fields = clsid.split("-")
     data1 = c_uint32(int(fields[0], 16))
     data2 = c_uint16(int(fields[1], 16))
     data3 = c_uint16(int(fields[2], 16))
     field4 = "".join(fields[3:])
     data4 = (c_ubyte * 8)()
     for i in xrange(0, 8):
         data4[i] = int(field4[i*2:2+i*2], 16)
     return GUID(data1, data2, data3, data4)
Exemple #18
0
    def createDevice(self):
        possible_paths = []
        for extension in get_so_extensions():
            possible_paths.append(
                os.path.abspath(
                    os.path.normpath(
                        os.path.join(
                            os.path.dirname(__file__),
                            '..',
                            'libuinput' + extension
                        )
                    )
                )
            )
        lib = None
        for path in possible_paths:
            if os.path.exists(path):
                lib = path
                break
        if not lib:
            raise OSError('Cant find libuinput. searched at:\n {}'.format(
                '\n'.join(possible_paths)
            )
        )

        self._lib = ctypes.CDLL(lib)

        c_k        = (ctypes.c_uint16 * len(self._k))(*self._k)
        c_a        = (ctypes.c_uint16 * len(self._a))(*self._a)
        c_amin     = (ctypes.c_int32  * len(self._amin ))(*self._amin )
        c_amax     = (ctypes.c_int32  * len(self._amax ))(*self._amax )
        c_afuzz    = (ctypes.c_int32  * len(self._afuzz))(*self._afuzz)
        c_aflat    = (ctypes.c_int32  * len(self._aflat))(*self._aflat)
        c_r        = (ctypes.c_uint16 * len(self._r))(*self._r)
        c_vendor   = ctypes.c_uint16(self.vendor)
        c_product  = ctypes.c_uint16(self.product)
        c_version  = ctypes.c_uint16(self.version)
        c_keyboard = ctypes.c_int(self.keyboard)

        c_name = ctypes.c_char_p(self.name)
        self._fd = self._lib.uinput_init(ctypes.c_int(len(self._k)),
                                         c_k,
                                         ctypes.c_int(len(self._a)),
                                         c_a,
                                         c_amin,
                                         c_amax,
                                         c_afuzz,
                                         c_aflat,
                                         ctypes.c_int(len(self._r)),
                                         c_r,
                                         c_keyboard,
                                         c_vendor,
                                         c_product,
                                         c_version,
                                         c_name)
Exemple #19
0
def evaluate(wire):
  try:
    if wire.isdigit():
      return c_uint16(int(wire))
  except:
    pass
  print(wires[wire], wire)
  value = wires[wire]
  if len(value) is 1:
    if value[0].isdigit():
      return c_uint16(int(value[0]))
    else:
      return evaluate(value[0])
  elif 'NOT' in value:
    if value[-1].isdigit():
      return c_uint16(~c_uint16(int(value[-1])).value)
    else:
      return c_uint16(~evaluate(value[-1]).value)
  elif 'LSHIFT' in value:
    return c_uint16(evaluate(value[0]).value << int(value[2])) 
  elif 'RSHIFT' in value:
    return c_uint16(evaluate(value[0]).value >> int(value[2]))
  elif 'AND' in value:
    return c_uint16(evaluate(value[0]).value & evaluate(value[2]).value)
  elif 'OR' in value:
    return c_uint16(evaluate(value[0]).value | evaluate(value[2]).value)
Exemple #20
0
    def get_pdu_length(self):
        """
        Returns info about the PDU length.
        """
        logger.info("getting PDU length")
        requested_ = c_uint16()
        negotiated_ = c_uint16()
        code = self.library.Cli_GetPduLength(self.pointer, byref(requested_), byref(negotiated_))
        check_error(code)

        return negotiated_.value
Exemple #21
0
    def setData(self, data, calculate_length=True, endian='big', crc_len = CRC_LEN_TX):
        data.reverse()

        if endian=='big':
            swap16 = lambda x: x
            swap32 = lambda x: x
            swapFloat = lambda x: x
        else:
            swap16 = _ByteSwap16
            swap32 = _ByteSwap32
            swapFloat = _ByteSwapFloat

        fd = Frame_Data_Fields()

        for i,d in enumerate(data):
            if type(d)==int:
                data[i] = ctypes.c_uint32(d)
            elif type(d)==float:
                data[i] = ctypes.c_float(d)

        totaldatabytelength = 0

        for b in data:

            entrysize = ctypes.sizeof(type(b))

            fd.raw[entrysize:] = fd.raw[:-entrysize]

            totaldatabytelength += entrysize

            if type(b)==ctypes.c_uint8:
                fd.var_uint8[0] = b
            elif type(b)==ctypes.c_int8:
                fd.var_int8[0] = b
            elif type(b)==ctypes.c_uint16:
                fd.var_uint16[0] = ctypes.c_uint16(swap16(b.value))
            elif type(b)==ctypes.c_int16:
                fd.var_int16[0] = ctypes.c_int16(swap16(b.value))
            elif type(b)==ctypes.c_uint32:
                fd.var_uint32[0] = ctypes.c_uint32(swap32(b.value))
            elif type(b)==ctypes.c_int32:
                fd.var_int32[0] = ctypes.c_int32(swap32(b.value))
            elif type(b)==ctypes.c_float:
                fd.var_float[0] = ctypes.c_float(swapFloat(b.value))

        if calculate_length:
            self.data_size = ctypes.c_uint16(swap16(totaldatabytelength))
            self.frame_size_raw = FRAME_HEADER_SIZE + totaldatabytelength + crc_len

        if crc_len == 1:
            crc = crc8_block([self.status])
            fd.raw[totaldatabytelength] = ctypes.c_uint8(crc8_block(fd.raw[:totaldatabytelength], crc))

        self.data = fd
def calc_checksum(data):
    result = 0
    for i in range(0, len(data) - 1, 2):
        result += data[i+1] * 256 + data[i]
    if (len(data) % 2) != 0:
        result += data[-1]

    result = (result >> 16) + c_uint16(result).value
    result = ~(result + (result >> 16))
    result = c_uint16(result).value

    return result
Exemple #23
0
    def __init__(self, vendor, product, name, keys, axes, rels, keyboard=False):
        self._lib = None
        self._k = keys
        if not axes or len(axes) == 0:
            self._a, self._amin, self._amax, self._afuzz, self._aflat = [[]] * 5
        else:
            self._a, self._amin, self._amax, self._afuzz, self._aflat = zip(*axes)

        self._r = rels
        possible_paths = []
        for extension in get_so_extensions():
            possible_paths.append(
                os.path.abspath(
                    os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "libuinput" + extension))
                )
            )
        lib = None
        for path in possible_paths:
            if os.path.exists(path):
                lib = path
                break
        if not lib:
            raise OSError("Cant find linuinput. searched at:\n {}".format("\n".join(possible_paths)))
        self._lib = ctypes.CDLL(lib)

        c_k = (ctypes.c_uint16 * len(self._k))(*self._k)
        c_a = (ctypes.c_uint16 * len(self._a))(*self._a)
        c_amin = (ctypes.c_int32 * len(self._amin))(*self._amin)
        c_amax = (ctypes.c_int32 * len(self._amax))(*self._amax)
        c_afuzz = (ctypes.c_int32 * len(self._afuzz))(*self._afuzz)
        c_aflat = (ctypes.c_int32 * len(self._aflat))(*self._aflat)
        c_r = (ctypes.c_uint16 * len(self._r))(*self._r)
        c_vendor = ctypes.c_uint16(vendor)
        c_product = ctypes.c_uint16(product)
        c_keyboard = ctypes.c_int(keyboard)

        c_name = ctypes.c_char_p(name)
        self._fd = self._lib.uinput_init(
            ctypes.c_int(len(self._k)),
            c_k,
            ctypes.c_int(len(self._a)),
            c_a,
            c_amin,
            c_amax,
            c_afuzz,
            c_aflat,
            ctypes.c_int(len(self._r)),
            c_r,
            c_keyboard,
            c_vendor,
            c_product,
            c_name,
        )
Exemple #24
0
 def apply_operator(operator, values):
     if operator == Operator.LShift:
         return ctypes.c_uint16(values[0] << values[1]).value
     if operator == Operator.RShift:
         return ctypes.c_uint16(values[0] >> values[1]).value
     if operator == Operator.And:
         return ctypes.c_uint16(values[0] & values[1]).value
     if operator == Operator.Or:
         return ctypes.c_uint16(values[0] | values[1]).value
     if operator == Operator.Not:
         return ctypes.c_uint16(~values[0]).value
     if operator == Operator.Noop:
         return values[0]
Exemple #25
0
 def NewObject(self, name, objectType, subType):
     if not self.status:
         raise Exception('Shotfile Header not open.')
     try:
         onam = c_char_p(name)
     except TypeError:
         onam = c_char_p(name.encode())
     onaml = c_uint64(len(name))
     error = c_int32(0)
     objtype = c_uint16(objectType)
     subtype = c_uint16(subType)
     libsfh.sfhnewobj_(byref(error), byref(self.sfhref), onam, byref(objtype), byref(subtype), onaml)
     GetError(error)
Exemple #26
0
    def set_connection_params(self, ip_address, tsap_snap7, tsap_logo):
        """
        Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates.
        This function must be called just before Cli_Connect().

        :param ip_address: IP ip_address of server
        :param tsap_snap7: TSAP SNAP7 Client (e.g. 10.00 = 0x1000)
        :param tsap_logo: TSAP Logo Server (e.g. 20.00 = 0x2000)
        """
        assert re.match(ipv4, ip_address), '%s is invalid ipv4' % ip_address
        result = self.library.Cli_SetConnectionParams(self.pointer, ip_address.encode(),
                                                      c_uint16(tsap_snap7),
                                                      c_uint16(tsap_logo))
        if result != 0:
            raise Snap7Exception("The parameter was invalid")
Exemple #27
0
    def set_connection_params(self, address, local_tsap, remote_tsap):
        """
        Sets internally (IP, LocalTSAP, RemoteTSAP) Coordinates.
        This function must be called just before Cli_Connect().

        :param address: PLC/Equipment IPV4 Address, for example "192.168.1.12"
        :param local_tsap: Local TSAP (PC TSAP)
        :param remote_tsap: Remote TSAP (PLC TSAP)
        """
        assert re.match(ipv4, address), '%s is invalid ipv4' % address
        result = self.library.Cli_SetConnectionParams(self.pointer, address,
                                                      c_uint16(local_tsap),
                                                      c_uint16(remote_tsap))
        if result != 0:
            raise Snap7Exception("The parameter was invalid")
Exemple #28
0
 def _get_roi(self):
     wRoiX0, wRoiY0, wRoiX1, wRoiY1 = (
         C.c_uint16(), C.c_uint16(),
         C.c_uint16(), C.c_uint16())
     dll.get_roi(self.camera_handle, wRoiX0, wRoiY0, wRoiX1, wRoiY1)
     if self.verbose:
         print(" Camera ROI:");
         print(" From pixel", wRoiX0.value, "to pixel", wRoiX1.value, "(left/right)")
         print(" From pixel", wRoiY0.value, "to pixel", wRoiY1.value, "(up/down)")
     self.roi = {
         'left': wRoiX0.value,
         'top': wRoiY0.value,
         'right': wRoiX1.value,
         'bottom': wRoiY1.value}
     return self.roi
def get_color():
    """Returns the rgb color measurement as a tuple.

    Note: An exception is thrown if it fails to get a measurement from
    the click.
    """
    red = ctypes.c_uint16(0)
    green = ctypes.c_uint16(0)
    blue = ctypes.c_uint16(0)
    ret = _LIB.color2_click_get_color(ctypes.byref(red),
                                      ctypes.byref(green),
                                      ctypes.byref(blue))
    if ret < 0:
        raise Exception("color2 click get color failed")
    return (red.value, green.value, blue.value)
Exemple #30
0
 def _lowLevelGetStreamingLatestValues(self, lpPs4000Ready,
                                       pParameter=c_void_p()):
     m = self.lib.ps4000aGetStreamingLatestValues(
         c_uint16(self.handle),
         lpPs4000Ready,
         pParameter)
     self.checkResult(m)
def audioConfigure(engine, handle, streamID, key, value):
    '''
    helper function to call teAudioConfigure
    '''
    return engine.teAudioConfigure(handle, ct.c_uint16(streamID),
                                   ct.c_uint16(key), ct.c_uint32(value))
Exemple #32
0
 def _lowLevelSetNoOfCaptures(self, numCaptures):
     m = self.lib.ps2000aSetNoOfCaptures(c_int16(self.handle),
                                         c_uint16(numCaptures))
     self.checkResult(m)
Exemple #33
0
    def _to_fs_entry(self, fs_config, out_file):
        """Converts an FSConfig entry to an fs entry.

        Writes the fs_config contents to the output file.

        Calls sys.exit() on error.

        Args:
            fs_config (FSConfig): The entry to convert to write to file.
            file (File): The file to write to.
        """

        # Get some short names
        mode = fs_config.mode
        user = fs_config.user
        group = fs_config.group
        caps = fs_config.caps
        path = fs_config.path

        emsg = 'Cannot convert "%s" to identifier!'

        # convert mode from octal string to integer
        mode = int(mode, 8)

        # remap names to values
        if AID.is_friendly(user):
            if user not in self._friendly_to_aid:
                sys.exit(emsg % user)
            user = self._friendly_to_aid[user].value
        else:
            if user not in self._id_to_aid:
                sys.exit(emsg % user)
            user = self._id_to_aid[user].value

        if AID.is_friendly(group):
            if group not in self._friendly_to_aid:
                sys.exit(emsg % group)
            group = self._friendly_to_aid[group].value
        else:
            if group not in self._id_to_aid:
                sys.exit(emsg % group)
            group = self._id_to_aid[group].value

        caps_dict = self._capability_parser.caps

        caps_value = 0

        try:
            # test if caps is an int
            caps_value = int(caps, 0)
        except ValueError:
            caps_split = caps.split(',')
            for cap in caps_split:
                if cap not in caps_dict:
                    sys.exit('Unknown cap "%s" found!' % cap)
                caps_value += 1 << caps_dict[cap]

        path_length_with_null = len(path) + 1
        path_length_aligned_64 = (path_length_with_null + 7) & ~7
        # 16 bytes of header plus the path length with alignment
        length = 16 + path_length_aligned_64

        length_binary = bytearray(ctypes.c_uint16(length))
        mode_binary = bytearray(ctypes.c_uint16(mode))
        user_binary = bytearray(ctypes.c_uint16(int(user, 0)))
        group_binary = bytearray(ctypes.c_uint16(int(group, 0)))
        caps_binary = bytearray(ctypes.c_uint64(caps_value))
        path_binary = ctypes.create_string_buffer(path,
                                                  path_length_aligned_64).raw

        out_file.write(length_binary)
        out_file.write(mode_binary)
        out_file.write(user_binary)
        out_file.write(group_binary)
        out_file.write(caps_binary)
        out_file.write(path_binary)
def assert_bn_testbit(x_old, i):
    bn_x = int_to_bignum(x_old)
    return_value = lib.bn_testbit(bn_x, c_uint16(i))

    assert return_value == x_old >> i & 1
Exemple #35
0
 def _set_bitratetype(self, value):
     self.base_structure.bitratetype = ctypes.c_uint16(int(value))
Exemple #36
0
 def _set_rating(self, value):
     self.base_structure.rating = ctypes.c_uint16(int(value))
Exemple #37
0
 def _set_nochannels(self, value):
     self.base_structure.nochannels = ctypes.c_uint16(int(value))
Exemple #38
0
 def _set_tracknumber(self, value):
     self.base_structure.tracknumber = ctypes.c_uint16(int(value))
Exemple #39
0
@copywrite, Ruizhe Lin and Peter Kner, University of Georgia, 2019
"""

import ctypes as ct
r11 = ct.windll.LoadLibrary('C:/Users/Public/Documents/python_code/QXGA/R11CommLib-1.7-x64.dll')

import subprocess
filepath = r'C:/Program Files/MetroCon-3.3/RepTools/RepSender.exe'

class Dev(ct.Structure):
    pass

Dev._fields_ = [("id", ct.c_char_p), ("next", ct.POINTER(Dev))]

NULL = ct.POINTER(ct.c_int)()
RS485_DEV_TIMEOUT = ct.c_uint16(1000)
RS485_BAUDRATE = ct.c_uint32(256000)
RS232_BAUDRATE = ct.c_uint32(115200)

def repsend(fns):
    output = subprocess.Popen([filepath, '-z', fns, '-d', '0175000547'],stdout=subprocess.PIPE).communicate()[0]
    print(output)
    
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')
Exemple #40
0
    def __init__(self,
                 vendor,
                 product,
                 version,
                 name,
                 keys,
                 axes,
                 rels,
                 keyboard=False,
                 rumble=False):
        self._lib = None
        self._k = keys
        self.name = name
        if not axes or len(axes) == 0:
            self._a, self._amin, self._amax, self._afuzz, self._aflat = [[]
                                                                         ] * 5
        else:
            self._a, self._amin, self._amax, self._afuzz, self._aflat = zip(
                *axes)

        self._r = rels

        base_path = os.path.dirname(__file__)
        # Search for libuinput.so
        lib, search_paths = None, []
        libname = "libuinput"
        so_extensions = [
            ext for ext, _, typ in imp.get_suffixes() if typ == imp.C_EXTENSION
        ]
        for extension in so_extensions:
            search_paths += [
                os.path.abspath(
                    os.path.normpath(
                        os.path.join(base_path, '..', libname + extension))),
                os.path.abspath(
                    os.path.normpath(
                        os.path.join(base_path, '../..', libname + extension)))
            ]
        for path in search_paths:
            if os.path.exists(path):
                lib = path
                break

        if not lib:
            raise OSError('Cant find libuinput. searched at:\n {}'.format(
                '\n'.join(search_paths)))
        self._lib = ctypes.CDLL(lib)
        self._ff_events = None
        if rumble:
            self._ff_events = (POINTER(FeedbackEvent) * MAX_FEEDBACK_EFFECTS)()
            for i in xrange(MAX_FEEDBACK_EFFECTS):
                self._ff_events[i].contents = FeedbackEvent()

        try:
            if self._lib.uinput_module_version() != UNPUT_MODULE_VERSION:
                raise Exception()
        except:
            import sys
            print >> sys.stderr, "Invalid native module version. Please, recompile 'libuinput.so'"
            print >> sys.stderr, "If you are running sc-controller from source, you can do this by removing 'build' directory"
            print >> sys.stderr, "and runinng 'python setup.py build' or 'run.sh' script"
            raise Exception("Invalid native module version")

        c_k = (ctypes.c_uint16 * len(self._k))(*self._k)
        c_a = (ctypes.c_uint16 * len(self._a))(*self._a)
        c_amin = (ctypes.c_int32 * len(self._amin))(*self._amin)
        c_amax = (ctypes.c_int32 * len(self._amax))(*self._amax)
        c_afuzz = (ctypes.c_int32 * len(self._afuzz))(*self._afuzz)
        c_aflat = (ctypes.c_int32 * len(self._aflat))(*self._aflat)
        c_r = (ctypes.c_uint16 * len(self._r))(*self._r)
        c_vendor = ctypes.c_uint16(vendor)
        c_product = ctypes.c_uint16(product)
        c_version = ctypes.c_uint16(version)
        c_keyboard = ctypes.c_int(keyboard)
        c_rumble = ctypes.c_int(MAX_FEEDBACK_EFFECTS if rumble else 0)
        c_name = ctypes.c_char_p(name)

        self._fd = self._lib.uinput_init(ctypes.c_int(len(self._k)), c_k,
                                         ctypes.c_int(len(self._a)), c_a,
                                         c_amin, c_amax, c_afuzz, c_aflat,
                                         ctypes.c_int(len(self._r)), c_r,
                                         c_keyboard, c_vendor, c_product,
                                         c_version, c_rumble, c_name)
        if self._fd < 0:
            raise CannotCreateUInputException(
                "Failed to create uinput device. Error code: %s" %
                (self._fd, ))