예제 #1
0
 def cmp(self, a, b):
     r = ctypes.c_short(ctypes.c_byte(a).value - ctypes.c_byte(b).value).value
     rs = ctypes.c_byte(a - b).value
     self.pc_state.P.set_N((0,1)[0x80 == (rs & 0x80)])    # Negative
     self.pc_state.P.set_Z((0,1)[rs == 0])              # Zero
     r = (a & 0xFF) - (b & 0xFF)
     self.pc_state.P.set_C((1,0)[0x100 == (r & 0x100)]) # Carry (not borrow)
예제 #2
0
    def subc(self, a, b, c):

        if 0 == self.pc_state.P.get_D():
            r  = ctypes.c_short(ctypes.c_byte(a).value - ctypes.c_byte(b).value - ctypes.c_byte(c).value).value
            rs = ctypes.c_byte((a - b - c) & 0xFF).value
            self.pc_state.P.set_N((0,1)[0x80 == (rs & 0x80)]) # Negative
            self.pc_state.P.set_Z((0,1)[rs == 0])   # Zero
            self.pc_state.P.set_V((0,1)[r != rs])   # Overflow

            r = a - b - c 
            self.pc_state.P.set_C((1,0)[0x100 == (r & 0x100)]) # Carry (not borrow
            result = a - b - c
        elif 1 == self.pc_state.P.get_D():
            # Decimal subtraction
            # FIXME need to fix flags

            r = ctypes.c_short(((a >> 4) & 0xF)* 10+ ((a & 0xF) %10) - (((b>>4) & 0xF)* 10 + ((b & 0xF) %10)) - c).value

            # rc = a + b + c
            self.pc_state.P.set_N((0,1)[r < 0])
            self.pc_state.P.set_Z((0,1)[r == 0x0])
            #  Need to check/fix conditions for V
            # self.pc_state.P.V = (rc != r) ? 1:0;   # Overflow
            self.pc_state.P.set_V(1)   # Overflow

            self.pc_state.P.set_C((0,1)[(r >= 0) and (r <= 99)])
            result = (((int(r/10) % 10) << 4) & 0xf0) + (r%10)

        return result & 0xFF
예제 #3
0
 def write_latch(self, mask, latch):
     """
     Sets the current port latch value (least significant four bits) from the
     device.
     """
     self._dll.SI_WriteLatch(self._handle, ctypes.c_byte(mask),
                             ctypes.c_byte(latch))
예제 #4
0
def SKF_EnumDev(bool):
    '''
    Enum the dev
    :param bool:int
    :param sznamelist:int or other types
    :param pulsize: int
    :return: the code number
    for instance:
    SKF_EnumDev(1,1)
    '''

    pulsize = ctypes.c_ulong()  # pulsize主要为输出值,为输出值得时候,返回namelist的大小,一开始可以为空
    enum_result1 = LoadDll().get().SKF_EnumDev(
        Bool(bool).get(), ctypes.c_byte(), ctypes.byref(pulsize))
    if enum_result1 == 0:
        print('第一次设备枚举成功,返回 : ' +
              str(enum_result1))  # + "\n设备名称所占空间大小为:" + str(pulsize.value))
    else:
        print("第一次设备枚举失败,返回错误码:" + str(enum_result1))
        sys.exit(1)
    namelist = ctypes.c_byte(pulsize.value)
    enum_result2 = LoadDll().get().SKF_EnumDev(
        Bool(bool).get(), ctypes.byref(namelist), ctypes.byref(pulsize))
    if enum_result2 == 0:
        print('第二次设备枚举成功,返回 : ' + str(enum_result2) + '\n设备名字为:' +
              str(chr(namelist.value)))
    else:
        print("第二次设备枚举失败,返回错误码:" + str(enum_result2))
        sys.exit(1)
    return namelist.value  # 返回的值是namelist
예제 #5
0
    def subc(self, a, b, c):

        if 0 == self.pc_state.P.get_D():
            r  = ctypes.c_short(ctypes.c_byte(a).value - ctypes.c_byte(b).value - ctypes.c_byte(c).value).value
            rs = ctypes.c_byte((a - b - c) & 0xFF).value
            self.pc_state.P.set_N((0,1)[0x80 == (rs & 0x80)]) # Negative
            self.pc_state.P.set_Z((0,1)[rs == 0])   # Zero
            self.pc_state.P.set_V((0,1)[r != rs])   # Overflow

            r = a - b - c 
            self.pc_state.P.set_C((1,0)[0x100 == (r & 0x100)]) # Carry (not borrow
            result = a - b - c
        elif 1 == self.pc_state.P.get_D():
            # Decimal subtraction
            # FIXME need to fix flags

            r = ctypes.c_short(((a >> 4) & 0xF)* 10+ ((a & 0xF) %10) - (((b>>4) & 0xF)* 10 + ((b & 0xF) %10)) - c).value

            # rc = a + b + c
            self.pc_state.P.set_N((0,1)[r < 0])
            self.pc_state.P.set_Z((0,1)[r == 0x0])
            #  Need to check/fix conditions for V
            # self.pc_state.P.V = (rc != r) ? 1:0;   # Overflow
            self.pc_state.P.set_V(1)   # Overflow

            self.pc_state.P.set_C((0,1)[(r >= 0) and (r <= 99)])
            result = (((int(r/10) % 10) << 4) & 0xf0) + (r%10)

        return result & 0xFF
예제 #6
0
    def msa_read(self, address, offset=0, count=64):
        """Read a stream of bytes from a SMB slave device.

        Args:
            address: Byte-aligned slave address.
            offset: Byte-aligned offset in slave address.
            count: Number of bytes to read (range: 1-512).

        Returns:
            Buffer with the data that was read.
        """
        TargetAddress = ct.c_char * 16
        off = TargetAddress(offset)
        buffer = []
        n_read = ct.c_byte(-1)
        _DLL.HidSmbus_AddressReadRequest(self.handle, (address & 0xFE), count,
                                         1, off)
        try:
            while n_read != 0 and self.smb_status()[0] != HID_SMBUS_S0.ERROR:
                size = max(count, 64)
                buf = ct.create_string_buffer(size)
                status = ct.c_byte(0)
                _DLL.HidSmbus_GetReadResponse(self.handle, ct.byref(status),
                                              buf, size, ct.byref(n_read))
                buffer += buf.raw[:n_read.value]
        except HidSmbusError as e:
            # Ignore timeout, return the data that was read
            if e.status != 0x12:
                raise
        return buffer
예제 #7
0
파일: dgti2c.py 프로젝트: doxycomp/dgtpi
 def process_incoming_clock_forever(self):
     but = ctypes.c_byte(0)
     buttime = ctypes.c_byte(0)
     while True:
         if self.lib.dgt3000GetButton(ctypes.pointer(but),
                                      ctypes.pointer(buttime)) == 1:
             ack3 = but.value
             if ack3 == 0x01:
                 logging.info("Button 0 pressed")
                 Display.show(Message.DGT_BUTTON, button=0)
             if ack3 == 0x02:
                 logging.info("Button 1 pressed")
                 Display.show(Message.DGT_BUTTON, button=1)
             if ack3 == 0x04:
                 logging.info("Button 2 pressed")
                 Display.show(Message.DGT_BUTTON, button=2)
             if ack3 == 0x08:
                 logging.info("Button 3 pressed")
                 Display.show(Message.DGT_BUTTON, button=3)
             if ack3 == 0x10:
                 logging.info("Button 4 pressed")
                 Display.show(Message.DGT_BUTTON, button=4)
             if ack3 == 0x20:
                 logging.info("Button on/off pressed")
             if ack3 == 0x40:
                 logging.info("Lever pressed")
         time.sleep(0.1)
예제 #8
0
    def addc(self, a, b, c):

        if 0 == self.pc_state.P.get_D():
            r  = ctypes.c_short(a + b + c).value
            rc = ctypes.c_byte(a + b + c).value
            self.pc_state.P.set_N((0,1)[0x80 == (rc & 0x80)])
            self.pc_state.P.set_Z((0,1)[rc == 0x0])
            self.pc_state.P.set_V((0,1)[rc != r])   # Overflow

            r = ((a & 0xFF) + (b & 0xFF) + c) & 0xFFFF
            self.pc_state.P.set_C((0,1)[0x100 == (r & 0x100)])
            result = (a + b + c)
        elif 1 == self.pc_state.P.get_D():
            # Decimal Addition
            # FIXME need to fix flags
            #
            r = ctypes.c_short(((a >> 4) & 0xF)* 10+ ((a & 0xF) %10) + ((b>>4) & 0xF)* 10 + ((b & 0xF) %10) + c).value
            rc = ctypes.c_byte(a + b + c).value # ???? TODO
            self.pc_state.P.set_N((0,1)[r < 0])
            self.pc_state.P.set_Z((0,1)[rc == 0x0])
            # self.pc_state.P.V = (rc != r) ? 1:0;   # Overflow

            self.pc_state.P.set_C((0,1)[(r > 99) or (r < 0)])
            result = ((((int(r/10) % 10) << 4) & 0xf0) + (r%10))

        return result & 0xFF
예제 #9
0
def __IntToC_ByteArray(ints):
    buff = (ctypes.c_byte * 4)()
    buff[3] = ctypes.c_byte((ints & 0xFF000000) >> 24)
    buff[2] = ctypes.c_byte((ints & 0x00FF0000) >> 16)
    buff[1] = ctypes.c_byte((ints & 0x0000FF00) >> 8)
    buff[0] = ctypes.c_byte(((ints & 0x000000FF)))
    return buff
예제 #10
0
 def cmp(self, a, b):
     r = ctypes.c_short(ctypes.c_byte(a).value - ctypes.c_byte(b).value).value
     rs = ctypes.c_byte(a - b).value
     self.pc_state.P.set_N((0,1)[0x80 == (rs & 0x80)])    # Negative
     self.pc_state.P.set_Z((0,1)[rs == 0])              # Zero
     r = (a & 0xFF) - (b & 0xFF)
     self.pc_state.P.set_C((1,0)[0x100 == (r & 0x100)]) # Carry (not borrow)
예제 #11
0
 def _set_relay_state(self, relay_num, state):
     """
     Set the given relay's state
     :type relay_num: int
     :param relay_num: the number of the relay to activate (starting at 1)
     :type state: int
     :param state: the state to set (can be RELAY_STATE_OFF or RELAY_STATE_ON)
     :rtype: bool
     :return: True if relay is set to "state", False otherwise
     """
     # get method from dll
     funcProto = ctypes.WINFUNCTYPE(ctypes.c_void_p, wintypes.LPSTR,
                                    ctypes.c_byte, ctypes.c_byte)
     jwRelaySetRelayState = funcProto(("jwRelaySetRelayState", self.__dll))
     # call the method
     strSerial = wintypes.LPSTR(self._serial_number)
     bRelayNum = ctypes.c_byte(relay_num)
     bState = ctypes.c_byte(state)
     jwRelaySetRelayState(strSerial, bRelayNum, bState)
     # check that operation succeeded
     is_relay_on = self.is_relay_on(relay_num)
     is_relay_set = (state == RELAY_STATE_ON
                     and is_relay_on) or (state == RELAY_STATE_OFF
                                          and not is_relay_on)
     return is_relay_set
예제 #12
0
파일: dgti2c.py 프로젝트: jromang/dgtpi
 def process_incoming_clock_forever(self):
     but = ctypes.c_byte(0)
     buttime = ctypes.c_byte(0)
     while True:
         if self.lib.dgt3000GetButton(ctypes.pointer(but), ctypes.pointer(buttime)) == 1:
             ack3 = but.value
             if ack3 == 0x01:
                 logging.info("Button 0 pressed")
                 Display.show(Message.DGT_BUTTON, button=0)
             if ack3 == 0x02:
                 logging.info("Button 1 pressed")
                 Display.show(Message.DGT_BUTTON, button=1)
             if ack3 == 0x04:
                 logging.info("Button 2 pressed")
                 Display.show(Message.DGT_BUTTON, button=2)
             if ack3 == 0x08:
                 logging.info("Button 3 pressed")
                 Display.show(Message.DGT_BUTTON, button=3)
             if ack3 == 0x10:
                 logging.info("Button 4 pressed")
                 Display.show(Message.DGT_BUTTON, button=4)
             if ack3 == 0x20:
                 logging.info("Button on/off pressed")
             if ack3 == 0x40:
                 logging.info("Lever pressed")
         time.sleep(0.1)
예제 #13
0
    def addc(self, a, b, c):

        if 0 == self.pc_state.P.get_D():
            r  = ctypes.c_short(a + b + c).value
            rc = ctypes.c_byte(a + b + c).value
            self.pc_state.P.set_N((0,1)[0x80 == (rc & 0x80)])
            self.pc_state.P.set_Z((0,1)[rc == 0x0])
            self.pc_state.P.set_V((0,1)[rc != r])   # Overflow

            r = ((a & 0xFF) + (b & 0xFF) + c) & 0xFFFF
            self.pc_state.P.set_C((0,1)[0x100 == (r & 0x100)])
            result = (a + b + c)
        elif 1 == self.pc_state.P.get_D():
            # Decimal Addition
            # FIXME need to fix flags
            #
            r = ctypes.c_short(((a >> 4) & 0xF)* 10+ ((a & 0xF) %10) + ((b>>4) & 0xF)* 10 + ((b & 0xF) %10) + c).value
            rc = ctypes.c_byte(a + b + c).value # ???? TODO
            self.pc_state.P.set_N((0,1)[r < 0])
            self.pc_state.P.set_Z((0,1)[rc == 0x0])
            # self.pc_state.P.V = (rc != r) ? 1:0;   # Overflow

            self.pc_state.P.set_C((0,1)[(r > 99) or (r < 0)])
            result = (((((r/10) % 10) << 4) & 0xf0) + (r%10))

        return result & 0xFF
예제 #14
0
def GetHidLibraryVersion():
    """Returns the SLABHIDDevice library version number as a string."""
    major = ct.c_byte()
    minor = ct.c_byte()
    release = ct.c_long()
    _DLL.HidSmbus_GetHidLibraryVersion(ct.byref(major), ct.byref(minor),
                                       ct.byref(release))
    return "{}.{}.{}".format(major.value, minor.value, release.value)
예제 #15
0
 def GetGpioConfig(self):
     dir = ct.c_byte()
     mode = ct.c_byte()
     fnc = ct.c_byte()
     div = ct.c_byte()
     _DLL.HidSmbus_GetGpioConfig(self.handle, ct.byref(dir), ct.byref(mode),
                                 ct.byref(fnc), ct.byref(div))
     return (dir.value, mode.value, fnc.value, div.value)
예제 #16
0
def glowIn(maxBrightness):

  for address in range(0, 1084):
      frameBuffer[address*packageSize + 0] = c_byte(address % 256) 
      frameBuffer[address*packageSize + 1] = c_byte(address / 256)
      frameBuffer[address*packageSize + offsetRed] = c_byte(maxBrightness)
      frameBuffer[address*packageSize + offsetGreen] = c_byte(maxBrightness)
      frameBuffer[address*packageSize + offsetBlue] = c_byte(maxBrightness)
  sendFrame(frameBuffer)
예제 #17
0
def colorOff(rangeTuple):
  for address in range(rangeTuple[0], rangeTuple[1]+1):
    frameBuffer[address*packageSize + 0] = c_byte(address % 256) 
    frameBuffer[address*packageSize + 1] = c_byte(address / 256)
    frameBuffer[address*packageSize + offsetRed] = c_byte(1)
    frameBuffer[address*packageSize + offsetGreen] = c_byte(1) 
    frameBuffer[address*packageSize + offsetBlue] = c_byte(1)
  
  sendFrame(frameBuffer)
예제 #18
0
def drawSign (signList, colorList):
  for address in signList:
    frameBuffer[address*packageSize + 0] = c_byte(address % 256) 
    frameBuffer[address*packageSize + 1] = c_byte(address / 256)
    frameBuffer[address*packageSize + offsetRed] = c_byte(colorList[0])
    frameBuffer[address*packageSize + offsetGreen] = c_byte(colorList[1]) 
    frameBuffer[address*packageSize + offsetBlue] = c_byte(colorList[2])
    
  sendFrame(frameBuffer)
예제 #19
0
파일: cardlib.py 프로젝트: hobbit19/PokerAI
def encode(card):
    """
    Ranks 2-14
    Suits 1-5
    """
    suitnum = card[1]
    if isinstance(card[1],str):
        suitnum = {'s': 1, 'h': 2,'d': 3,'c': 4}.get(card[1], 0)
    return lib.encode(ctypes.c_byte(card[0] - 2), ctypes.c_byte(suitnum - 1))
예제 #20
0
 def GetUartStatus(self):
     tx_fifo = ct.c_ushort(0)
     rx_fifo = ct.c_ushort(0)
     err_stat = ct.c_byte(0)
     lbr_stat = ct.c_byte(0)
     _DLL.HidUart_GetUartStatus(self.handle, ct.byref(tx_fifo),
                                ct.byref(rx_fifo), ct.byref(err_stat),
                                ct.byref(lbr_stat))
     return (tx_fifo.value, rx_fifo.value, err_stat.value, lbr_stat.value)
예제 #21
0
def glowSign (signList, glowLevel):
  
  for address in signList:
    frameBuffer[address*packageSize + 0] = c_byte(address % 256) 
    frameBuffer[address*packageSize + 1] = c_byte(address / 256)
    frameBuffer[address*packageSize + offsetRed] = c_byte(glowLevel)
    frameBuffer[address*packageSize + offsetGreen] = c_byte(glowLevel) 
    frameBuffer[address*packageSize + offsetBlue] = c_byte(glowLevel)
    
  sendFrame(frameBuffer)
예제 #22
0
def MIDI_GetEvt(take, evtidx, selectedOut, mutedOut, ppqposOut, msg, msg_sz):
    a = _RPR._ft['MIDI_GetEvt']
    f = ct.CFUNCTYPE(ct.c_byte, ct.c_uint64, ct.c_int, ct.c_void_p,
                     ct.c_void_p, ct.c_void_p, ct.c_char_p, ct.c_void_p)(a)
    t = (_RPR.rpr_packp('MediaItem_Take*', take), ct.c_int(evtidx),
         ct.c_byte(selectedOut), ct.c_byte(mutedOut), ct.c_double(ppqposOut),
         packs_l(msg), ct.c_int(msg_sz))
    r = f(t[0], t[1], ct.byref(t[2]), ct.byref(t[3]), ct.byref(t[4]), t[5],
          ct.byref(t[6]))
    return (r, take, evtidx, int(t[2].value), int(t[3].value),
            float(t[4].value), unpacks_l(t[5]), int(t[6].value))
예제 #23
0
def MIDI_SetEvt(p0, p1, p2, p3, p4, p5, p6, p7):
    a = _RPR._ft['MIDI_SetEvt']
    f = ct.CFUNCTYPE(ct.c_byte, ct.c_uint64, ct.c_int, ct.c_void_p,
                     ct.c_void_p, ct.c_void_p, ct.c_char_p, ct.c_int,
                     ct.c_void_p)(a)
    t = (_RPR.rpr_packp('MediaItem_Take*',
                        p0), ct.c_int(p1), ct.c_byte(p2), ct.c_byte(p3),
         ct.c_double(p4), packs_l(p5), ct.c_int(p6), ct.c_byte(p7))
    r = f(t[0], t[1], ct.byref(t[2]), ct.byref(t[3]), ct.byref(t[4]), t[5],
          t[6], ct.byref(t[7]))
    return (r, p0, p1, int(t[2].value), int(t[3].value), float(t[4].value), p5,
            p6, int(t[7].value))
예제 #24
0
def colorFillSide(sideDic, colorList):
  
  colorList = colorProtect (colorList)
  
  for address in range(sideDic['startAddr'], sideDic['endAddr'] + 1):
    if (address <> -1):
      frameBuffer[address*packageSize + 0] = c_byte(address % 256) 
      frameBuffer[address*packageSize + 1] = c_byte(address / 256)
      frameBuffer[address*packageSize + offsetRed] = c_byte(colorList[0])
      frameBuffer[address*packageSize + offsetGreen] = c_byte(colorList[1]) 
      frameBuffer[address*packageSize + offsetBlue] = c_byte(colorList[2])

  sendFrame(frameBuffer)
예제 #25
0
def colorFill(list, colorList):

  colorList = colorProtect (colorList)
  
  for address in list:
    if (address <> -1):
      frameBuffer[address*packageSize + 0] = c_byte(address % 256) 
      frameBuffer[address*packageSize + 1] = c_byte(address / 256)
      frameBuffer[address*packageSize + offsetRed] = c_byte(colorList[0])
      frameBuffer[address*packageSize + offsetGreen] = c_byte(colorList[1]) 
      frameBuffer[address*packageSize + offsetBlue] = c_byte(colorList[2])

  sendFrame(frameBuffer)
예제 #26
0
def wholeGlowOut(glowTime, maxBrightness):
  
  sleepTime = float(glowTime) / float(maxBrightness)
  
  for i in range(maxBrightness, 1, -1):
    for address in range(0, 1084):
        frameBuffer[address*packageSize + 0] = c_byte(address % 256) 
        frameBuffer[address*packageSize + 1] = c_byte(address / 256)
        frameBuffer[address*packageSize + offsetRed] = c_byte(i)
        frameBuffer[address*packageSize + offsetGreen] = c_byte(i)
        frameBuffer[address*packageSize + offsetBlue] = c_byte(i)
    sendFrame(frameBuffer)
    sleep(sleepTime)
예제 #27
0
    def read_bfee(self, raw_bytes):
        # print(len(raw_bytes))
        self.timestamp_low = raw_bytes[0] + (raw_bytes[1] << 8)\
            + (raw_bytes[2] << 16) + (raw_bytes[3] << 24)
        self.bfee_count = raw_bytes[4] + (raw_bytes[5] << 8)
        self.Nrx = raw_bytes[8]
        self.Ntx = raw_bytes[9]
        self.rssi_a = raw_bytes[10]
        self.rssi_b = raw_bytes[11]
        self.rssi_c = raw_bytes[12]
        self.noise = c_byte(raw_bytes[13]).value
        self.agc = raw_bytes[14]
        self.antenna_sel = raw_bytes[15]
        self.len = raw_bytes[16] + (raw_bytes[17] << 8)
        self.fake_rate_n_flags = raw_bytes[18] + (raw_bytes[19] << 8)
        self.calc_len = (30 * (self.Nrx * self.Ntx * 8 * 2 + 3) + 7) // 8

        payload = raw_bytes[20:]

        # Check that length matches what it should
        assert self.len == self.calc_len

        # Compute CSI from all this crap :)
        index = 0
        remainder = 0
        self.csi = []
        for i in range(30):
            index += 3
            remainder = index % 8
            for j in range(self.Ntx * self.Nrx):
                tmp_real = (payload[index // 8] >> remainder) |\
                (payload[index // 8 + 1] << (8 - remainder))
                # print(c_int8(tmp_real).value == c_byte(tmp_real).value)
                tmp_real = c_byte(tmp_real).value
                # print("%x %x %d"%(payload[index // 8], payload[index // 8 + 1], tmp_real))

                tmp_imag = (payload[index // 8 + 1] >> remainder) |\
                (payload[index // 8 + 2] << (8 - remainder))
                tmp_imag = c_byte(tmp_imag).value
                self.csi.append(complex(tmp_real, tmp_imag))
                index += 16
        self.perm = []
        # print(bin(self.antenna_sel))
        self.perm.append((self.antenna_sel & 0x3) + 1)
        self.perm.append((self.antenna_sel >> 2 & 0x3) + 1)
        self.perm.append((self.antenna_sel >> 4 & 0x3) + 1)
        self.csi = np.array(self.csi).\
            reshape((30, self.Nrx, self.Ntx)).transpose()
        # print(self.csi)
        self.csi[:, :] = self.csi[:, [idx - 1 for idx in self.perm]]
예제 #28
0
    def Connect(self):
        self.ftd2xxDll = ctypes.windll.LoadLibrary('ftd2xx.dll')
        self.handle = ctypes.wintypes.DWORD()
        assert self.ftd2xxDll.FT_Open(0, ctypes.byref(self.handle)) == 0

        assert self.ftd2xxDll.FT_SetTimeouts(self.handle, 1, 1) == 0
        assert self.ftd2xxDll.FT_SetBaudRate(self.handle, 38400) == 0
        assert self.ftd2xxDll.FT_SetDataCharacteristics(
            self.handle, ctypes.c_byte(8), ctypes.c_ubyte(0),
            ctypes.c_ubyte(0)) == 0
        assert self.ftd2xxDll.FT_SetFlowControl(self.handle, 0x0000,
                                                ctypes.c_byte(0),
                                                ctypes.c_byte(0)) == 0
        assert self.ftd2xxDll.FT_Purge(self.handle, 3) == 0
예제 #29
0
 def output(self, high):
     if high:
         c_data = ctypes.c_byte(1)
     else:
         c_data = ctypes.c_byte(0)
     c_written = ctypes.c_long(0)
     with getLockForBoard(self.board_number):
         checkStatus(
             nidaqmx.DAQmxWriteDigitalLines(
                 self.taskHandle, ctypes.c_long(1), ctypes.c_long(1),
                 ctypes.c_double(10.0),
                 ctypes.c_long(DAQmx_Val_GroupByChannel),
                 ctypes.byref(c_data), ctypes.byref(c_written), None))
     assert c_written.value == 1, "Digital output failed"
예제 #30
0
def MIDI_InsertEvt(take, selected, muted, ppqpos, bytestr, bytestr_sz):
    a = _RPR._ft["MIDI_InsertEvt"]
    f = ct.CFUNCTYPE(
        ct.c_byte, ct.c_uint64, ct.c_byte, ct.c_byte, ct.c_double, ct.c_char_p,
        ct.c_int
    )(a)
    return f(
        _RPR.rpr_packp("MediaItem_Take*", take),
        ct.c_byte(selected),
        ct.c_byte(muted),
        ct.c_double(ppqpos),
        packs_l(bytestr),
        ct.c_int(bytestr_sz)
    )
예제 #31
0
def canJump(row, col, player, pos):
    """
	Returns 1 if we can jump to the left 2 if we can jump to the right 3 if we can jump
	both directions and 0 if no jump is possible row,col can be empty. So it can also be
	used to determine if we can make a jump from a position we do not occupy.
	Caution!!! does no checks if we are inside the board
	:param row:
	:param col:
	:param player:
	:param pos:
	:return:
	"""
    return board_lib.canJump(c_byte(row), c_byte(col), c_byte(player),
                             pointer(pos))
예제 #32
0
def canJumpTo(row, col, player, pos, rowDest, colDest):
    """
	Like canJump() it doesn't need row, col to be occupied by a piece.
	Caution!!! does no checks if we are inside board
	:param row:
	:param col:
	:param player:
	:param pos:
	:param rowDest:
	:param colDest:
	:return:
	"""
    return bool(
        board_lib.canJumpTo(c_byte(row), c_byte(col), c_byte(player),
                            pointer(pos), c_byte(rowDest), c_byte(colDest)))
예제 #33
0
 def flush_buffers(self, flush_transmit=False, flush_receive=False):
     """
     On USB MCU devices, this function flushes both the receive buffer in
     the USBXpress device driver and the transmit buffer in the device. Note:
     Parameter 2 and 3 have no effect and any value can be passed when used
     with USB MCU devices. On CP210x devices, this function operates in
     accordance with parameters 2 and 3. If parameter 2 (flush_transmit) is
     non-zero, the CP210x device's UART transmit buffer is flushed. If
     parameter 3 (flush_receive) is non-zero, the CP210x device's UART
     receive buffer is flushed. If parameters 2 and 3 are both non-zero,
     then both the CP210x device UART transmit buffer and UART receive
     buffer are flushed.
     """
     self._dll.SI_FlushBuffers(self._handle, ctypes.c_byte(flush_transmit),
                               ctypes.c_byte(flush_receive))
예제 #34
0
def wholeColorOut(outTime, colorList):
  
  colorList = colorProtect (colorList)
  sleepTime = float(outTime) / float(255)
  
  for i in range(255, 1, -1):
    for address in range(0, 1084):
        frameBuffer[address*packageSize + 0] = c_byte(address % 256) 
        frameBuffer[address*packageSize + 1] = c_byte(address / 256)
        frameBuffer[address*packageSize + offsetRed] = c_byte(i)
        frameBuffer[address*packageSize + offsetGreen] = c_byte(i)
        frameBuffer[address*packageSize + offsetBlue] = c_byte(i)
    
    sendFrame(frameBuffer)
    sleep(sleepTime)
예제 #35
0
    def discovery(self, dongle):
        # control settings
        uuid = galileo.main.FitBitUUID
        service1 = 0xfb00
        write = 0xfb01
        read = 0xfb02
        minDuration = 4000

        # start discovery
        data = galileo.utils.i2lsba(uuid.int, 16)
        for i in (service1, write, read, minDuration):
            data += galileo.utils.i2lsba(i, 2)
        dongle.ctrl_write(galileo.dongle.CM(4, data))

        # find fitbits
        while True:
            d = dongle.ctrl_read(minDuration)
            if galileo.dongle.isStatus(d, 'StartDiscovery', False): continue
            elif d.INS == 2: break

            ID = sanitize(galileo.utils.a2x(d.payload[:6], ''))
            RSSI = c_byte(d.payload[7]).value
            yield [ID, RSSI]

        # stop discovery
        dongle.ctrl_write(galileo.dongle.CM(5))
        galileo.dongle.isStatus(dongle.ctrl_read(), 'CancelDiscovery')
예제 #36
0
 def set_bit(self,c, bit, value):
     """Set a single data bit on the darlington board"""
     if 'board' not in c:
         raise NoDeviceSelectedError()
     if (bit < 1) or (bit > self.nChannels[c['board']]):
         raise NoSuchChannel()
     yield self.dll.SetDataBit(c['board'], c_byte(bit), value)
예제 #37
0
 def fromStr(self, argStr):
     valStr = self.time.fromStr(argStr)
     nibbleSeq = self.hexStr2NibbleSeq(valStr)
     assert len(nibbleSeq) < MAX_ARRAY_SIZE
     self.numNibbles = len(nibbleSeq)
     for idx, nibble in enumerate(nibbleSeq):
         self.nibbles[idx] = ctypes.c_byte(nibble)
예제 #38
0
 def _hmove_clocks(self, hm):
     # hm - int8
     # Need to ensure 'hm' maintains negative when shifted.
     clock_shift = 0
     # 'hm >= 0x80' is negative move.
     clock_shift = ctypes.c_byte(hm).value >> 4
     return clock_shift
예제 #39
0
    def  __init__(self, anchors, edge_length=0.25, distance_margin=1.5):
        """
        Initialise with a dictionary of anchors (id->(x,y), and other parameters)
        """
        super(LeDLL, self).__init__()
        
        self.anchors = anchors
        self.edge_length = edge_length
        self.distance_margin = distance_margin
        
        anchors_array_type = ctypes.c_double * (len(anchors) * 2)
        anchors_array = anchors_array_type()
        
        distances_array_type = ctypes.c_double * len(anchors)
        self.distances_array = distances_array_type()
        self.n_distance = ctypes.c_ubyte(len(anchors))
        
        location_array_type = ctypes.c_double * 2
        self.location_array = location_array_type()
        
        anchor_ids = anchors.keys()
        anchor_ids.sort()
        self.anchor_ids = anchor_ids
        
        for i, anchor_id in enumerate(anchor_ids):
            x, y = anchors[anchor_id]
            anchors_array[i * 2] = x
            anchors_array[i * 2 + 1] = y

        handle = self.le_create(ctypes.c_double(edge_length), 
                                ctypes.c_double(distance_margin), 
                                ctypes.c_byte(len(anchors)), 
                                anchors_array)
        self.handle = ctypes.c_int(handle)
예제 #40
0
파일: ctfribidi.py 프로젝트: olpa/tex
def log2levels(s, pbase_dir):
  (c_buf1, c_buf2, n) = _preamble(s)
  c_dir = ctypes.c_byte(pbase_dir)
  c_levels = (ctypes.c_byte * n)()
  ctypes.cast(c_levels, ctypes.POINTER(ctypes.c_byte))
  fb.fribidi_log2vis(c_buf1, n, ctypes.byref(c_dir), None, None, None, c_levels)
  return c_levels
예제 #41
0
파일: rpm.py 프로젝트: powergun/GLHF
 def __init__(self, hProcess, is64Bit=True):
     self.hProcess = hProcess
     self.addressTypeConv = ctypes.c_ulonglong if is64Bit else ctypes.c_uint
     
     self.intBuffer = ctypes.c_int() 
     self.intBufferSize = ctypes.sizeof(self.intBuffer)
     
     self.uintBuffer = ctypes.c_uint()
     self.uintBufferSize = ctypes.sizeof(self.uintBuffer)
     
     self.int64Buffer = ctypes.c_longlong()
     self.int64BufferSize = ctypes.sizeof(self.int64Buffer)
     
     self.uint64Buffer = ctypes.c_ulonglong()
     self.uint64BufferSize = ctypes.sizeof(self.uint64Buffer)
     
     self.floatBuffer = ctypes.c_float()
     self.floatBufferSize = ctypes.sizeof(self.floatBuffer)
     
     self.vec4Buffer = vector.C_VECTOR4()
     self.vec4BufferSize = ctypes.sizeof(self.vec4Buffer)
     
     self.mat4Buffer = matrix.C_MATRIX()
     self.mat4BufferSize = ctypes.sizeof(self.mat4Buffer)
     
     self.str64Buffer = common.STR64()
     self.str64BufferSize = ctypes.sizeof(self.str64Buffer)
     
     self.byteBuffer = ctypes.c_byte()
     self.byteBufferSize = ctypes.sizeof(self.byteBuffer)
 def writeByte(self, byte):
   try:
     self.writeBuffer(str(ctypes.c_byte(byte).value))
   except TypeError:
     self._logger.error('TXML Protocol: Invalid byte value %s') % (byte)
     return -1
   return 0
    def write_vk(self, vk_code): # {{{
        logging.debug('virtual key code' + str(vk_code))

        li = INPUT_RECORD * 1

        # create keyboard input
        ke = KEY_EVENT_RECORD()
        ke.uChar.UnicodeChar = u(chr(0))
        ke.wVirtualKeyCode = ctypes.c_short(int(vk_code))
        ke.wVirtualScanCode = ctypes.c_short(ctypes.windll.user32.MapVirtualKeyW(int(vk_code), 0))
        ke.bKeyDown = ctypes.c_byte(1)
        ke.wRepeatCount = ctypes.c_short(1)

        # set enhanced key mode for arrow keys
        if vk_code in CONQUE_WINDOWS_VK_ENHANCED:
            logging.debug('enhanced key!')
            ke.dwControlKeyState = ENHANCED_KEY

        kc = INPUT_RECORD(KEY_EVENT)
        kc.Event.KeyEvent = ke
        list_input = li(kc)

        # write input array
        events_written = ctypes.c_int()
        res = ctypes.windll.kernel32.WriteConsoleInputW(self.stdin, list_input, 1, ctypes.byref(events_written))

        logging.debug('bar')
        logging.debug('events written ' + str(events_written))
        logging.debug(str(res))
        logging.debug(str(ctypes.GetLastError()))
        logging.debug(str(ctypes.FormatError(ctypes.GetLastError())))
예제 #44
0
 def output(self, high):
     if high:
         c_data = ctypes.c_byte(1)
     else:
         c_data = ctypes.c_byte(0)
     c_written = ctypes.c_long(0)
     with getLockForBoard(self.board_number):
         checkStatus(nidaqmx.DAQmxWriteDigitalLines(self.taskHandle,
                                                ctypes.c_long(1),
                                                ctypes.c_long(1),
                                                ctypes.c_double(10.0),
                                                ctypes.c_long(DAQmx_Val_GroupByChannel),
                                                ctypes.byref(c_data),
                                                ctypes.byref(c_written),
                                                None))
     assert c_written.value == 1, "Digital output failed"
 def get_ad9361_rf_rssi(self, channel=0):
     rf_rssi = RF_RSSI()
     g_lib.ad9361_get_rx_rssi(g_rf_phy, ctypes.c_byte(channel), ctypes.byref(rf_rssi))
     try:
         rssi = -1.0 * float(rf_rssi.symbol) / float(rf_rssi.multiplier)
     except:
         rssi = None
     return rssi
예제 #46
0
	def __init__(self, dtsVersion=24, exporterVersion=0):
		self.dtsVersion = dtsVersion
		self.exporterVersion = exporterVersion
		self.sequence32 = c_int(0)
		self.sequence16 = c_short(0)
		self.sequence8  = c_byte(0)
		self.buffer32 = []
		self.buffer16 = []
		self.buffer8  = []
예제 #47
0
 def write_marker_byte(self, marker, value):
     """
         EXPORTSPEC int DECL2 daveWriteBytes(daveConnection * dc, int area, int DB, int start,
                                             int len, void * buffer);
         write a flag (8-bit) to the plc
     """
     buffer = ctypes.c_byte(int(value))
     buffer_p =  ctypes.pointer(buffer)
     self.dave.daveWriteBytes(self.dc, daveFlags, 0, marker, 1, buffer_p)
예제 #48
0
def _fixCArg(a):
    if isinstance(a, unicode):
        a = a.encode("utf-8")
    if isinstance(a, str):
        a = ctypes.c_char_p(a)
    if isinstance(a, ctypes.c_char_p) or (isinstance(a, _ctypes._Pointer) and a._type_ is ctypes.c_char):
        return ctypes.cast(a, ctypes.POINTER(ctypes.c_byte))
    if isinstance(a, ctypes.c_char):
        return ctypes.c_byte(ord(a.value))
    return a
예제 #49
0
def fillRows(sideDic, topRow, bottomRow, colorList):
      
      colorList = colorProtect (colorList)
            
      if (bottomRow > sideDic['endRow']):
        bottomRow = sideDic['endRow']
      if (topRow < sideDic['startRow']):
        topRow = sideDic['startRow']
      
      for row in range(topRow, bottomRow + 1):
        for address in sideDic[str(row)]:
          if (address <> -1):
            frameBuffer[address*packageSize + 0] = c_byte(address % 256) 
            frameBuffer[address*packageSize + 1] = c_byte(address / 256)
            frameBuffer[address*packageSize + offsetRed] = c_byte(colorList[0])
            frameBuffer[address*packageSize + offsetGreen] = c_byte(colorList[1]) 
            frameBuffer[address*packageSize + offsetBlue] = c_byte(colorList[2])
        
      sendFrame(frameBuffer)
예제 #50
0
 def func(n, z):
     assert c_int(n)
     assert not c_int(z)
     assert c_int(-1)
     assert not c_byte(z)
     assert not c_char(chr(z))
     # assert not c_float(z)
     assert not c_double(z)
     assert not c_ulonglong(bigzero)
     assert c_ulonglong(big)
예제 #51
0
 def write_vm_byte(self, vm, value):
     """
         EXPORTSPEC int DECL2 daveWriteBytes(daveConnection * dc, int area, int DB, int start,
                                             int len, void * buffer);
         ein Merkerbyte in die SPS schreiben
         TODO: anpassen und testen
     """
     buffer = ctypes.c_byte(int(value))
     buffer_p =  ctypes.pointer(buffer)
     self.dave.daveWriteBytes(self.dc, daveDB, 1, vm, 1, buffer_p)
예제 #52
0
def TreeSetUsage(ctx,n,usage):
    """Set node usage"""
    try:
        status = __TreeShr._TreeSetUsage(ctx,_C.c_int32(n),_C.c_byte(usage))
    except:
        raise TreeException("Feature not present in current MDSplus installation. Upgrade to newer version of MDSplus.")
    if (status & 1):
        return
    else:
        raise TreeException(MdsGetMsg(status))