⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dongle.py

📁 USB在FPGA上的实现
💻 PY
📖 第 1 页 / 共 4 页
字号:
#! /usr/bin/python
# -*- coding: ISO-8859-1 -*-

##########################################################################
# LPC Dongle programming software 
#
# Copyright (C) 2008 Artec Design
# 
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# 
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##########################################################################

#-------------------------------------------------------------------------
# Project:   LPC Dongle programming software 
# Name:      dongle.py
# Purpose:   Executable command line tool 
#
# Author:    J黵i Toomessoo <jyrit@artecdesign.ee>
# Copyright: (c) 2008 by Artec Design
# Licence:   LGPL
#
# Created:   06 Oct. 2006
# History:   12 oct. 2006  Version 1.0 released
#            22 Feb. 2007  Test options added to test PCB board
#            10 Nov. 2007  Added open retry code to dongle
#            14 Nov. 2007  Moved dongle spesific code to class Dongle from USPP
#                          USPP is allmost standard now (standard USPP would work)
#                          Artec USPP has serial open retry
#            14 Nov. 2007  Improved help. 
#            10 Mar. 2008  Forced code to hw flow control settings made linux 1 byte read to 2 bytes
#                          as dongle never reads 1 byte at the time
#            18 Apr. 2008  Added file size boundary check on write to see if remaining size from
#                          given offset fits the file size

#            24 Apr. 2008  Mac OS X support by Stefan Reinauer <stepan@coresystems.de>
#-------------------------------------------------------------------------

import os
import sys
import string
import time
import struct
from sets import *
from struct import *

#### inline of artec FTDI spesific Uspp code ###################################################

##########################################################################
# USPP Library (Universal Serial Port Python Library)
#
# Copyright (C) 2006 Isaac Barona <ibarona@gmail.com>
# 
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# 
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
##########################################################################

#-------------------------------------------------------------------------
# Project:   USPP Library (Universal Serial Port Python Library)
# Name:      uspp.py
# Purpose:   Main module. Imports the correct module for the platform
#            in which it is running.
#
# Author:    Isaac Barona Martinez <ibarona@gmail.com>
# Contributors:
#            Damien G閞anton <dgeranton@voila.fr>
#            Douglas Jones <dfj23@drexel.edu>
#            J.Grauheding <juergen.grauheding@a-city.de>
#            J.Toomessoo jyrit@artecdesign.ee
#
# Copyright: (c) 2006 by Isaac Barona Martinez
# Licence:   LGPL
#
# Created:   26 June 2001
# History:
#            05/08/2001: Release version 0.1.
#            24/02/2006: Final version 1.0.
#            10/11/2007: Added open retry code to dongle
#                        by Jyri Toomessoo jyrit@artecdesign.ee
#            14/11/2007: Moved dongle spesific code to class Dongle from USPP
#                        USPP is allmost standard now (standard USPP would work)
#                        Artec USPP has serial open retry
#                        by Jyri Toomessoo jyrit@artecdesign.ee
#            10/03/2008: Forced code to hw flow control settings made linux 1 byte read to 2 bytes
#                        as dongle never reads 1 byte at the time
#                        by Jyri Toomessoo jyrit@artecdesign.ee
#            10/03/2008: Copose single infile bundle for FTDI USB serial 1.2
#                        this is nonuniversal modification of the code to suite the need of Artec Design Dongle
#                        by Jyri Toomessoo jyrit@artecdesign.ee
#-------------------------------------------------------------------------


drv_ok = 0
if sys.platform=='win32':
    print "Windows platform detected:"
    if drv_ok == 0:
        try:
            from win32file import *
            from win32event import *
            import win32con
            import exceptions
            
            print "Using VCP FTDI driver"
        except ImportError,SerialPortException:        
            print "Python for winiows extensions for COM not found" 
            print "(see https://sourceforge.net/projects/pywin32/)"
            print "Could not find any usable support for FTDI chip in python"
            print "Try installing python support from one of the links."
            sys.exit()
elif sys.platform=='linux2':
    from termios import *
    import fcntl
    import exceptions
    import array
    print "Linux platform detected:"
elif sys.platform=='darwin':
    from termios import *
    import fcntl
    import exceptions
    import array
    print "Mac OS X platform detected:"
else:
    sys.exit('Sorry, no implementation for this platform yet')



class SerialPortException(exceptions.Exception):
    """Exception raise in the SerialPort methods"""
    def __init__(self, args=None):
        self.args=args
    def __str__(self):
        return repr(self.args)

    
if sys.platform=='win32':    
  class SerialPortWin:
    BaudRatesDic={110: CBR_110,
                  300: CBR_300,
                  600: CBR_600,
                  1200: CBR_1200,
                  2400: CBR_2400,
                  4800: CBR_4800, 
                  9600: CBR_9600,
                  19200: CBR_19200,
                  38400: CBR_38400,
                  57600: CBR_57600,
                  115200: CBR_115200,
                  128000: CBR_128000,
                  256000: CBR_256000
                  }

    def __init__(self, dev, timeout=None, speed=115200, mode='232', params=None):
        self.__devName, self.__timeout, self.__speed=dev, timeout, speed
        self.__mode=mode
        self.__params=params
        self.__speed = 0
        self.__reopen = 0
        while 1:
            try:
                self.__handle=CreateFile (dev,
                win32con.GENERIC_READ|win32con.GENERIC_WRITE,
                0, # exclusive access
                None, # no security
                win32con.OPEN_EXISTING,
                win32con.FILE_ATTRIBUTE_NORMAL,
                None)
                break
                        
            except:
                n=0
                while (n < 2000000):
                    n += 1;                
                self.__reopen = self.__reopen + 1
            if self.__reopen > 32:
                print "Port does not exist..."
                raise SerialPortException('Port does not exist...')
                break
                #sys.exit()
        self.__configure()

    def __del__(self):
        if self.__speed:
            try:
                CloseHandle(self.__handle)
            except:
                raise SerialPortException('Unable to close port')


            

    def __configure(self):
        if not self.__speed:
            self.__speed=115200
        # Tell the port we want a notification on each char
        SetCommMask(self.__handle, EV_RXCHAR)
        # Setup a 4k buffer
        SetupComm(self.__handle, 4096, 4096)
        # Remove anything that was there
        PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
                  PURGE_RXCLEAR)
        if self.__timeout==None:
            timeouts= 0, 0, 0, 0, 0
        elif self.__timeout==0:
            timeouts = win32con.MAXDWORD, 0, 0, 0, 1000
        else:
            timeouts= self.__timeout, 0, self.__timeout, 0 , 1000
        SetCommTimeouts(self.__handle, timeouts)

        # Setup the connection info
        dcb=GetCommState(self.__handle)
        dcb.BaudRate=SerialPortWin.BaudRatesDic[self.__speed]
        if not self.__params:
            dcb.ByteSize=8
            dcb.Parity=NOPARITY
            dcb.StopBits=ONESTOPBIT
            dcb.fRtsControl=RTS_CONTROL_ENABLE
            dcb.fOutxCtsFlow=1
        else:
            dcb.ByteSize, dcb.Parity, dcb.StopBits=self.__params
        SetCommState(self.__handle, dcb)
        

    def fileno(self):
        return self.__handle


    def read(self, num=1):
        (Br, buff) = ReadFile(self.__handle, num)
        if len(buff)<>num and self.__timeout!=0: # Time-out  
            print 'Expected %i bytes but got %i before timeout'%(num,len(buff))
            raise SerialPortException('Timeout')
        else:
            return buff


    def readline(self):
        s = ''
        while not '\n' in s:
            s = s+SerialPortWin.read(self,1)

        return s 


    def write(self, s):
        """Write the string s to the serial port"""
        errCode = 0
        overlapped=OVERLAPPED()
        overlapped.hEvent=CreateEvent(None, 0,0, None)
        (errCode, bytesWritten) = WriteFile(self.__handle, s,overlapped)
        # Wait for the write to complete
        WaitForSingleObject(overlapped.hEvent, INFINITE)
        return bytesWritten
        
    def inWaiting(self):
        """Returns the number of bytes waiting to be read"""
        flags, comstat = ClearCommError(self.__handle)
        return comstat.cbInQue

    def flush(self):
        """Discards all bytes from the output or input buffer"""
        PurgeComm(self.__handle, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|
                  PURGE_RXCLEAR)


                  
if sys.platform=='linux2':
  class SerialPortLin:
    """Encapsulate methods for accesing to a serial port."""

    BaudRatesDic={
        110: B110,
        300: B300,
        600: B600,
        1200: B1200,
        2400: B2400,
        4800: B4800, 
        9600: B9600,
        19200: B19200,
        38400: B38400,
        57600: B57600,
        115200: B115200,
        230400: B230400
        }
    buf = array.array('h', '\000'*4)

    def __init__(self, dev, timeout=None, speed=115200, mode='232', params=None):
        self.__devName, self.__timeout, self.__speed=dev, timeout, speed
        self.__mode=mode
        self.__params=params
        self.__speed = 0
        self.__reopen = 0
        while 1:
            try:
                self.__handle=os.open(dev, os.O_RDWR)
                break
                        
            except:
                n=0
                while (n < 2000000):
                    n += 1;                
                self.__reopen = self.__reopen + 1
            if self.__reopen > 32:
                print "Port does not exist..."
                raise SerialPortException('Port does not exist...')
                break

        self.__configure()

    def __del__(self):
	if self.__speed:
            #tcsetattr(self.__handle, TCSANOW, self.__oldmode)
            pass
            try:
                pass
                os.close(self.__handle)
            except IOError:
                raise SerialPortException('Unable to close port')


    def __configure(self):
        if not self.__speed:
            self.__speed=115200
        
        # Save the initial port configuration
        self.__oldmode=tcgetattr(self.__handle)
        if not self.__params:
            # print "Create linux params for serialport..."
            # self.__params is a list of attributes of the file descriptor
            # self.__handle as follows:
            # [c_iflag, c_oflag, c_cflag, c_lflag, c_ispeed, c_ospeed, cc]

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -