Created
March 14, 2013 12:46
-
-
Save zeha/5161040 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ctypes | |
__all__ = ['FtdiSerial', 'FtdiException', 'FtdiTimeoutException'] | |
libftdi = ctypes.CDLL('libftd2xx.so') | |
FT_OK = 0 | |
class FtdiException(Exception): | |
pass | |
class FtdiTimeoutException(Exception): | |
pass | |
class FtdiSerial(object): | |
def __init__(self, deviceNumber, speed): | |
self._timeout = 30 | |
rv = libftdi.FT_SetVIDPID(ctypes.c_uint(0x0403), ctypes.c_uint(0x6001)) | |
self._handle = ctypes.c_void_p() | |
rv = libftdi.FT_Open(ctypes.c_int(deviceNumber), ctypes.byref(self._handle)) | |
if rv != FT_OK: | |
raise FtdiException('FT_Open returned %d' % rv) | |
rv = libftdi.FT_SetBaudRate(self._handle, speed) | |
if rv != FT_OK: | |
raise FtdiException('FT_SetBaudRate returned %d' % rv) | |
def __del__(self): | |
libftdi.FT_Close(self._handle) | |
@property | |
def timeout(self): | |
return self._timeout | |
@timeout.setter | |
def timeout(self, value): | |
self._timeout = value | |
rv = libftdi.FT_SetTimeouts(self._handle, ctypes.c_int(int(value*1000)), ctypes.c_int(int(value*1000))) | |
if rv != FT_OK: | |
raise FtdiException('FT_SetTimeouts returned %d' % rv) | |
def read(self, size): | |
buffer = b' ' * size | |
dwBytesRead = ctypes.c_uint(0) | |
rv = libftdi.FT_Read(self._handle, buffer, size, ctypes.byref(dwBytesRead)) | |
if rv != FT_OK: | |
raise FtdiException('FT_Read returned %d' % rv) | |
if dwBytesRead.value != size: | |
raise FtdiTimeoutException() | |
return buffer | |
def write(self, data): | |
dwBytesWritten = ctypes.c_uint(0) | |
buf_size = len(data) | |
rv = libftdi.FT_Write(self._handle, data, buf_size, ctypes.byref(dwBytesWritten)) | |
if rv != FT_OK: | |
raise FtdiException('FT_Write returned %d' % rv) | |
while dwBytesWritten.value != buf_size: | |
# untested :) | |
data = data[dwBytesWritten.value:] | |
buf_size = len(data) | |
if buf_size == 0: | |
# done | |
break | |
rv = libftdi.FT_Write(self._handle, data, buf_size, ctypes.byref(dwBytesWritten)) | |
if rv != FT_OK: | |
raise FtdiException('FT_Write returned %d' % rv) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment