Python ctypes.c_ushort() Examples

The following are 30 code examples of ctypes.c_ushort(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ctypes , or try the search function .
Example #1
Source File: CRCCCITT.py    From PyCRC with GNU General Public License v3.0 6 votes vote down vote up
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 = self.starting_value

            for c in input_data:
                d = ord(c) if is_string else c
                tmp = (c_ushort(crcValue >> 8).value) ^ d
                crcValue = (c_ushort(crcValue << 8).value) ^ int(
                    self.crc_ccitt_tab[tmp], 0)

            return crcValue
        except Exception as e:
            print("EXCEPTION(calculate): {}".format(e)) 
Example #2
Source File: control_test.py    From iroko with Apache License 2.0 6 votes vote down vote up
def adjust_rate(ctrl_iface, rate=1e6):
    log.info(f"Setting rate to {rate}")
    bw_lib = ctypes.CDLL(f"{FILE_DIR}/dc_gym/control/libbw_control.so")
    bw_lib.init_ring.argtypes = [
        ctypes.c_char_p, ctypes.c_ushort, ctypes.c_uint]
    bw_lib.init_ring.restype = ctypes.POINTER(Ring)
    bw_lib.send_bw.argtypes = [
        ctypes.c_uint32, ctypes.POINTER(Ring), ctypes.c_ushort]
    bw_lib.send_bw.restype = ctypes.c_int
    bw_lib.wait_for_reply.argtypes = [ctypes.POINTER(Ring)]
    rx_ring = bw_lib.init_ring(
        ctrl_iface.encode("ascii"), SRC_PORT,
        PACKET_RX_RING)
    tx_ring = bw_lib.init_ring(
        ctrl_iface.encode("ascii"), SRC_PORT,
        PACKET_TX_RING)
    bw_lib.send_bw(int(rate), tx_ring, DST_PORT)
    bw_lib.wait_for_reply(rx_ring) 
Example #3
Source File: ircsnapshot.py    From ircsnapshot with MIT License 6 votes vote down vote up
def is_ipv6(ip):
    try:
        if os.name == "nt":
            class sockaddr(ctypes.Structure):
                _fields_ = [("sa_family", ctypes.c_short),
                            ("__pad1", ctypes.c_ushort),
                            ("ipv4_addr", ctypes.c_byte * 4),
                            ("ipv6_addr", ctypes.c_byte * 16),
                            ("__pad2", ctypes.c_ulong)]

            WSAStringToAddressA = ctypes.windll.ws2_32.WSAStringToAddressA
            addr = sockaddr()
            addr.sa_family = socket.AF_INET6
            addr_size = ctypes.c_int(ctypes.sizeof(addr))
            if WSAStringToAddressA(ip, socket.AF_INET6, None, ctypes.byref(addr), ctypes.byref(addr_size)) != 0:
                raise socket.error(ctypes.FormatError())
            return ctypes.string_at(addr.ipv6_addr, 16)
        else:
            return socket.inet_pton(socket.AF_INET6, ip)
    except:
        return False 
Example #4
Source File: _multi_proc.py    From pyresample with GNU Lesser General Public License v3.0 6 votes vote down vote up
def shmem_as_ndarray(raw_array):
    _ctypes_to_numpy = {
        ctypes.c_char: np.int8,
        ctypes.c_wchar: np.int16,
        ctypes.c_byte: np.int8,
        ctypes.c_ubyte: np.uint8,
        ctypes.c_short: np.int16,
        ctypes.c_ushort: np.uint16,
        ctypes.c_int: np.int32,
        ctypes.c_uint: np.int32,
        ctypes.c_long: np.int32,
        ctypes.c_ulong: np.int32,
        ctypes.c_float: np.float32,
        ctypes.c_double: np.float64
    }
    dtype = _ctypes_to_numpy[raw_array._type_]

    # The following works too, but occasionally raises
    # RuntimeWarning: Item size computed from the PEP 3118 buffer format string does not match the actual item size.
    # and appears to be slower.
    # return np.ctypeslib.as_array(raw_array)

    return np.frombuffer(raw_array, dtype=dtype) 
Example #5
Source File: context_vidmode.py    From csgo_dont_blind_me with GNU General Public License v3.0 6 votes vote down vote up
def set_ramp(self, ramp):
        display = self._display
        screen_num = self._screen_num

        ramp_size = self.ramp_size
        _ramp = (c_ushort * ramp_size * 3)()

        for i in range(3):
            for j in range(ramp_size):
                _ramp[i][j] = int(C_USHORT_MAX * ramp[i][j])

        gamma_r = byref(_ramp, 0 * ramp_size * C_USHORT_SIZE)
        gamma_g = byref(_ramp, 1 * ramp_size * C_USHORT_SIZE)
        gamma_b = byref(_ramp, 2 * ramp_size * C_USHORT_SIZE)

        if not XF86VidModeSetGammaRamp(display, screen_num, ramp_size,
                                       gamma_r, gamma_g, gamma_b):
            raise ContextError('Unable to set gamma ramp') 
Example #6
Source File: context_vidmode.py    From csgo_dont_blind_me with GNU General Public License v3.0 6 votes vote down vote up
def get_ramp(self):
        display = self._display
        screen_num = self._screen_num

        ramp_size = self.ramp_size
        ramp = (c_ushort * ramp_size * 3)()

        gamma_r = byref(ramp, 0 * ramp_size * C_USHORT_SIZE)
        gamma_g = byref(ramp, 1 * ramp_size * C_USHORT_SIZE)
        gamma_b = byref(ramp, 2 * ramp_size * C_USHORT_SIZE)

        if not XF86VidModeGetGammaRamp(display, screen_num, ramp_size,
                                       gamma_r, gamma_g, gamma_b):
            raise ContextError('Unable to get gamma ramp')

        return [[ramp[i][j] / C_USHORT_MAX for j in range(ramp_size)]
                for i in range(3)] 
Example #7
Source File: parsers.py    From dsmr_parser with MIT License 6 votes vote down vote up
def crc16(telegram):
        crc16_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 ^ 0xA001
                else:
                    crc = c_ushort(crc >> 1).value
            crc16_tab.append(hex(crc))

        crcValue = 0x0000

        for c in telegram:
            d = ord(c)
            tmp = crcValue ^ d
            rotated = c_ushort(crcValue >> 8).value
            crcValue = rotated ^ int(crc16_tab[(tmp & 0x00ff)], 0)

        return crcValue 
Example #8
Source File: pypyodbc.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def win_create_mdb(mdb_path, sort_order = "General\0\0"):
    if sys.platform not in ('win32','cli'):
        raise Exception('This function is available for use in Windows only.')
    
    mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d]
    if mdb_driver == []:
        raise Exception('Access Driver is not found.')
    else:
        driver_name = mdb_driver[0].encode('mbcs')


    #CREATE_DB=<path name> <sort order>
    ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p]

    if py_v3:
        c_Path =  bytes("CREATE_DB=" + mdb_path + " " + sort_order,'mbcs')
    else:
        c_Path =  "CREATE_DB=" + mdb_path + " " + sort_order
    ODBC_ADD_SYS_DSN = 1
    
    
    ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path)
    if not ret:
        raise Exception('Failed to create Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %mdb_path) 
Example #9
Source File: pypyodbc.py    From edwin with Apache License 2.0 6 votes vote down vote up
def win_compact_mdb(mdb_path, compacted_mdb_path, sort_order = "General\0\0"):
    if sys.platform not in ('win32','cli'):
        raise Exception('This function is available for use in Windows only.')
    
    
    mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d]
    if mdb_driver == []:
        raise Exception('Access Driver is not found.')
    else:
        driver_name = mdb_driver[0].encode('mbcs')
    
    #COMPACT_DB=<source path> <destination path> <sort order>
    ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p]
    #driver_name = "Microsoft Access Driver (*.mdb)"
    if py_v3:
        c_Path = bytes("COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order,'mbcs')
        #driver_name = bytes(driver_name,'mbcs')
    else:
        c_Path = "COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order

    ODBC_ADD_SYS_DSN = 1
    ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path)
    if not ret:
        raise Exception('Failed to compact Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %compacted_mdb_path) 
Example #10
Source File: pypyodbc.py    From edwin with Apache License 2.0 6 votes vote down vote up
def win_create_mdb(mdb_path, sort_order = "General\0\0"):
    if sys.platform not in ('win32','cli'):
        raise Exception('This function is available for use in Windows only.')
    
    mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d]
    if mdb_driver == []:
        raise Exception('Access Driver is not found.')
    else:
        driver_name = mdb_driver[0].encode('mbcs')


    #CREATE_DB=<path name> <sort order>
    ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p]

    if py_v3:
        c_Path =  bytes("CREATE_DB=" + mdb_path + " " + sort_order,'mbcs')
    else:
        c_Path =  "CREATE_DB=" + mdb_path + " " + sort_order
    ODBC_ADD_SYS_DSN = 1
    
    
    ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path)
    if not ret:
        raise Exception('Failed to create Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %mdb_path) 
Example #11
Source File: pypyodbc.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def win_compact_mdb(mdb_path, compacted_mdb_path, sort_order = "General\0\0"):
    if sys.platform not in ('win32','cli'):
        raise Exception('This function is available for use in Windows only.')
    
    
    mdb_driver = [d for d in drivers() if 'Microsoft Access Driver (*.mdb' in d]
    if mdb_driver == []:
        raise Exception('Access Driver is not found.')
    else:
        driver_name = mdb_driver[0].encode('mbcs')
    
    #COMPACT_DB=<source path> <destination path> <sort order>
    ctypes.windll.ODBCCP32.SQLConfigDataSource.argtypes = [ctypes.c_void_p,ctypes.c_ushort,ctypes.c_char_p,ctypes.c_char_p]
    #driver_name = "Microsoft Access Driver (*.mdb)"
    if py_v3:
        c_Path = bytes("COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order,'mbcs')
        #driver_name = bytes(driver_name,'mbcs')
    else:
        c_Path = "COMPACT_DB=" + mdb_path + " " + compacted_mdb_path + " " + sort_order

    ODBC_ADD_SYS_DSN = 1
    ret = ctypes.windll.ODBCCP32.SQLConfigDataSource(None,ODBC_ADD_SYS_DSN,driver_name, c_Path)
    if not ret:
        raise Exception('Failed to compact Access mdb file - "%s". Please check file path, permission and Access driver readiness.' %compacted_mdb_path) 
Example #12
Source File: glfw.py    From pg with MIT License 6 votes vote down vote up
def wrap(self, gammaramp):
        '''
        Wraps a nested python sequence.
        '''
        red, green, blue = gammaramp
        size = min(len(red), len(green), len(blue))
        array_type = ctypes.c_ushort*size
        self.size = ctypes.c_uint(size)
        self.red_array = array_type()
        self.green_array = array_type()
        self.blue_array = array_type()
        for i in range(self.size):
            self.red_array[i] = int(red[i]*65535)
            self.green_array[i] = int(green[i]*65535)
            self.blue_array[i] = int(blue[i]*65535)
        pointer_type = ctypes.POINTER(ctypes.c_ushort)
        self.red = ctypes.cast(self.red_array, pointer_type)
        self.green = ctypes.cast(self.green_array, pointer_type)
        self.blue = ctypes.cast(self.blue_array, pointer_type) 
Example #13
Source File: artnet_message.py    From BiblioPixel with MIT License 6 votes vote down vote up
def MessageClass(length=DMX_LENGTH):
    assert 0 <= length <= DMX_LENGTH
    assert length % 2 == 0, 'artnet only takes messages of even length'

    Char, Int8, Int16 = ctypes.c_char, ctypes.c_ubyte, ctypes.c_ushort

    class DMXMessage(ctypes.Structure):
        # http://artisticlicence.com/WebSiteMaster/User%20Guides/art-net.pdf p47
        _fields_ = [
            ('id', Char * 8),
            ('opCode', Int16),
            ('protVerHi', Int8),
            ('protVerLo', Int8),
            ('sequence', Int8),
            ('physical', Int8),
            ('subUni', Int8),
            ('net', Int8),
            ('lengthHi', Int8),
            ('length', Int8),
            ('data', Int8 * length),  # At position 18
        ]

    return DMXMessage 
Example #14
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_Firmware(self, channel):
        """Get device firmware version
        Retrieves the firmvare version numbers for the device connected to
        channel.
        Args:
            channel (int): The channel you are interested in
        Returns:
            major (int): The major version number
            minor (int): The minor version number
            build (int): The build number
        """
        self.fn = inspect.currentframe().f_code.co_name
        buf_type = ct.c_ushort * 4
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CARD_FIRMWARE_REV,
                                   ct.byref(buf), ct.sizeof(buf))
        (build, release, minor, major) = struct.unpack('HHHH', buf)
        return (major, minor, build) 
Example #15
Source File: canlib.py    From Udacity-SDC-Radar-Driver-Micro-Challenge with MIT License 6 votes vote down vote up
def getChannelData_Firmware(self, channel):
        """Get device firmware version
        Retrieves the firmvare version numbers for the device connected to
        channel.
        Args:
            channel (int): The channel you are interested in
        Returns:
            major (int): The major version number
            minor (int): The minor version number
            build (int): The build number
        """
        self.fn = inspect.currentframe().f_code.co_name
        buf_type = ct.c_ushort * 4
        buf = buf_type()
        self.dll.canGetChannelData(channel,
                                   canCHANNELDATA_CARD_FIRMWARE_REV,
                                   ct.byref(buf), ct.sizeof(buf))
        (build, release, minor, major) = struct.unpack('HHHH', buf)
        return (major, minor, build) 
Example #16
Source File: CRC16.py    From PyCRC with GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example #17
Source File: CRC16.py    From PyCRC with GNU General Public License v3.0 5 votes vote down vote up
def init_crc16(self):
        '''The algorithm uses 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)) 
Example #18
Source File: CRCCCITT.py    From PyCRC with GNU General Public License v3.0 5 votes vote down vote up
def init_crc_ccitt(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_tab.append(hex(crc)) 
Example #19
Source File: CRC16DNP.py    From PyCRC with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #20
Source File: CRC16Kermit.py    From PyCRC with GNU General Public License v3.0 5 votes vote down vote up
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

            for c in input_data:
                d = ord(c) if is_string else c
                tmp = crcValue ^ d
                crcValue = c_ushort(crcValue >> 8).value ^ int(
                    self.crc16kermit_tab[(tmp & 0x00ff)], 0)

            # After processing, the one's complement of the CRC is calculated 
            # and 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)) 
Example #21
Source File: CRC16Kermit.py    From PyCRC with GNU General Public License v3.0 5 votes vote down vote up
def init_crc16kermit(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.crc16Kermit_constant
                else:
                    crc = c_ushort(crc >> 1).value
            self.crc16kermit_tab.append(hex(crc)) 
Example #22
Source File: hidapi_types.py    From msi-perkeyrgb with MIT License 5 votes vote down vote up
def set_hidapi_types(hidapi):

    hidapi.hid_init.argtypes = []
    hidapi.hid_init.restype = ct.c_int
    hidapi.hid_exit.argtypes = []
    hidapi.hid_exit.restype = ct.c_int
    hidapi.hid_enumerate.argtypes = [ct.c_ushort, ct.c_ushort]
    # hidapi.hid_enumerate.restype = ct.POINTER(DeviceInfo)
    # hidapi.hid_free_enumeration.argtypes = [ct.POINTER(DeviceInfo)]
    hidapi.hid_free_enumeration.restype = None
    hidapi.hid_open.argtypes = [ct.c_ushort, ct.c_ushort, ct.c_wchar_p]
    hidapi.hid_open.restype = ct.c_void_p
    hidapi.hid_open_path.argtypes = [ct.c_char_p]
    hidapi.hid_open_path.restype = ct.c_void_p
    hidapi.hid_write.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_size_t]
    hidapi.hid_write.restype = ct.c_int
    hidapi.hid_read_timeout.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_size_t, ct.c_int]
    hidapi.hid_read_timeout.restype = ct.c_int
    hidapi.hid_read.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_size_t]
    hidapi.hid_read.restype = ct.c_int
    hidapi.hid_set_nonblocking.argtypes = [ct.c_void_p, ct.c_int]
    hidapi.hid_set_nonblocking.restype = ct.c_int
    hidapi.hid_send_feature_report.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_int]
    hidapi.hid_send_feature_report.restype = ct.c_int
    hidapi.hid_get_feature_report.argtypes = [ct.c_void_p, ct.c_char_p, ct.c_size_t]
    hidapi.hid_get_feature_report.restype = ct.c_int
    hidapi.hid_close.argtypes = [ct.c_void_p]
    hidapi.hid_close.restype = None
    hidapi.hid_get_manufacturer_string.argtypes = [ct.c_void_p, ct.c_wchar_p, ct.c_size_t]
    hidapi.hid_get_manufacturer_string.restype = ct.c_int
    hidapi.hid_get_product_string.argtypes = [ct.c_void_p, ct.c_wchar_p, ct.c_size_t]
    hidapi.hid_get_product_string.restype = ct.c_int
    hidapi.hid_get_serial_number_string.argtypes = [ct.c_void_p, ct.c_wchar_p, ct.c_size_t]
    hidapi.hid_get_serial_number_string = ct.c_int
    hidapi.hid_get_indexed_string.argtypes = [ct.c_void_p, ct.c_int, ct.c_wchar_p, ct.c_size_t]
    hidapi.hid_get_indexed_string.restype = ct.c_int
    hidapi.hid_error.argtypes = [ct.c_void_p]
    hidapi.hid_error.restype = ct.c_wchar_p 
Example #23
Source File: pybass.py    From pybass with Apache License 2.0 5 votes vote down vote up
def LOWORD(a): return (ctypes.c_ushort)(a) 
Example #24
Source File: iroko_bw_control.py    From iroko with Apache License 2.0 5 votes vote down vote up
def init_backend(self):
        bw_lib = ctypes.CDLL(FILE_DIR + "/libbw_control.so")
        bw_lib.init_ring.argtypes = [
            ctypes.c_char_p, ctypes.c_ushort, ctypes.c_uint]
        bw_lib.init_ring.restype = ctypes.POINTER(Ring)
        bw_lib.send_bw.argtypes = [
            ctypes.c_uint32, ctypes.POINTER(Ring), ctypes.c_ushort]
        bw_lib.send_bw.restype = ctypes.c_int
        bw_lib.wait_for_reply.argtypes = [ctypes.POINTER(Ring)]
        return bw_lib 
Example #25
Source File: __init__.py    From python-broadlink with MIT License 5 votes vote down vote up
def calculate_crc16(self, input_data):
        from ctypes import c_ushort
        crc16_tab = []
        crc16_constant = 0xA001

        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 ^ crc16_constant
                else:
                    crc = c_ushort(crc >> 1).value
            crc16_tab.append(hex(crc))

        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 = 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(crc16_tab[(tmp & 0x00ff)], 0)

            return crcValue
        except Exception as e:
            print("EXCEPTION(calculate): {}".format(e)) 
Example #26
Source File: climate.py    From hysen with Apache License 2.0 5 votes vote down vote up
def calculate_crc16(self, input_data):
        from ctypes import c_ushort
        crc16_tab = []
        crc16_constant = 0xA001

        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 ^ crc16_constant
                else:
                    crc = c_ushort(crc >> 1).value
            crc16_tab.append(hex(crc))

        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 = 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(crc16_tab[(tmp & 0x00ff)], 0)

            return crcValue
        except Exception as e:
            print("EXCEPTION(calculate): {}".format(e)) 
Example #27
Source File: pybass.py    From pybass with Apache License 2.0 5 votes vote down vote up
def MAKEWORD(a,b): return (ctypes.c_ushort)(((a)&0xff)|((b)<<8)) 
Example #28
Source File: pybass.py    From pybass with Apache License 2.0 5 votes vote down vote up
def HIWORD(a): return (ctypes.c_ushort)((a)>>16) 
Example #29
Source File: pypyodbc.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare(self, query_string):
        """prepare a query"""
        
        #self._free_results(FREE_STATEMENT)

        if type(query_string) == unicode:
            c_query_string = wchar_pointer(UCS_buf(query_string))
            ret = ODBC_API.SQLPrepareW(self.stmt_h, c_query_string, len(query_string))
        else:
            c_query_string = ctypes.c_char_p(query_string)
            ret = ODBC_API.SQLPrepare(self.stmt_h, c_query_string, len(query_string))
        if ret != SQL_SUCCESS:
            check_success(self, ret)
            
        
        self._PARAM_SQL_TYPE_LIST = [] 
        
        if self.connection.support_SQLDescribeParam:
            # SQLServer's SQLDescribeParam only supports DML SQL, so avoid the SELECT statement
            if True:# 'SELECT' not in query_string.upper():
                #self._free_results(NO_FREE_STATEMENT)
                NumParams = c_short()
                ret = ODBC_API.SQLNumParams(self.stmt_h, ADDR(NumParams))
                if ret != SQL_SUCCESS:
                    check_success(self, ret)
            
                for col_num in range(NumParams.value):
                    ParameterNumber = ctypes.c_ushort(col_num + 1)
                    DataType = c_short()
                    ParameterSize = ctypes.c_size_t()
                    DecimalDigits = c_short()
                    Nullable = c_short()
                    ret = ODBC_API.SQLDescribeParam(
                        self.stmt_h,
                        ParameterNumber,
                        ADDR(DataType),
                        ADDR(ParameterSize),
                        ADDR(DecimalDigits),
                        ADDR(Nullable),
                    )
                    if ret != SQL_SUCCESS:
                        try:
                            check_success(self, ret)
                        except DatabaseError:
                            if sys.exc_info()[1].value[0] == '07009':
                                self._PARAM_SQL_TYPE_LIST = [] 
                                break
                            else:
                                raise sys.exc_info()[1]
                        except:
                            raise sys.exc_info()[1]

                    self._PARAM_SQL_TYPE_LIST.append((DataType.value,DecimalDigits.value))
        
        self.statement = query_string 
Example #30
Source File: pypyodbc.py    From termite-visualizations with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def getinfo(self,infotype):
        if infotype not in list(aInfoTypes.keys()):
            raise ProgrammingError('HY000','Invalid getinfo value: '+str(infotype)) 
        
        
        if aInfoTypes[infotype] == 'GI_UINTEGER':
            total_buf_len = 1000
            alloc_buffer = ctypes.c_ulong()
            used_buf_len = c_short()
            ret = ODBC_API.SQLGetInfo(self.dbc_h,infotype,ADDR(alloc_buffer), total_buf_len,\
                    ADDR(used_buf_len))
            check_success(self, ret)
            result = alloc_buffer.value
            
        elif aInfoTypes[infotype] == 'GI_USMALLINT':
            total_buf_len = 1000
            alloc_buffer = ctypes.c_ushort()
            used_buf_len = c_short()
            ret = ODBC_API.SQLGetInfo(self.dbc_h,infotype,ADDR(alloc_buffer), total_buf_len,\
                    ADDR(used_buf_len))
            check_success(self, ret)
            result = alloc_buffer.value

        else:
            total_buf_len = 1000
            alloc_buffer = create_buffer(total_buf_len)
            used_buf_len = c_short()
            if self.ansi:
                API_f = ODBC_API.SQLGetInfo
            else:
                API_f = ODBC_API.SQLGetInfoW
            ret = API_f(self.dbc_h,infotype,ADDR(alloc_buffer), total_buf_len,\
                    ADDR(used_buf_len))
            check_success(self, ret)
            if self.ansi:
                result = alloc_buffer.value
            else:
                result = UCS_dec(alloc_buffer)
            if aInfoTypes[infotype] == 'GI_YESNO':
                if unicode(result[0]) == unicode('Y'):
                    result = True
                else:
                    result = False
                    
        return result