You can subscribe to this list here.
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(1) |
Oct
|
Nov
|
Dec
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
2008 |
Jan
(10) |
Feb
(10) |
Mar
|
Apr
(1) |
May
|
Jun
|
Jul
|
Aug
(17) |
Sep
(9) |
Oct
(10) |
Nov
(2) |
Dec
(5) |
2009 |
Jan
(17) |
Feb
(8) |
Mar
(10) |
Apr
(1) |
May
|
Jun
(11) |
Jul
(18) |
Aug
|
Sep
|
Oct
(10) |
Nov
(40) |
Dec
(4) |
2010 |
Jan
(2) |
Feb
(5) |
Mar
(13) |
Apr
(14) |
May
(27) |
Jun
(86) |
Jul
(1) |
Aug
(12) |
Sep
|
Oct
(2) |
Nov
(3) |
Dec
(5) |
2011 |
Jan
|
Feb
(2) |
Mar
|
Apr
(3) |
May
|
Jun
|
Jul
(11) |
Aug
(1) |
Sep
(3) |
Oct
(65) |
Nov
|
Dec
(1) |
2012 |
Jan
(1) |
Feb
(4) |
Mar
(6) |
Apr
(6) |
May
|
Jun
(4) |
Jul
|
Aug
|
Sep
(12) |
Oct
(3) |
Nov
(1) |
Dec
|
2013 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(3) |
Nov
|
Dec
(1) |
2014 |
Jan
(2) |
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(1) |
Sep
(4) |
Oct
(1) |
Nov
(24) |
Dec
(10) |
2015 |
Jan
(1) |
Feb
(10) |
Mar
|
Apr
|
May
(1) |
Jun
(15) |
Jul
(4) |
Aug
(2) |
Sep
(1) |
Oct
|
Nov
|
Dec
|
From: <lu...@us...> - 2010-06-09 11:43:44
|
Revision: 455 http://pyscard.svn.sourceforge.net/pyscard/?rev=455&view=rev Author: ludov Date: 2010-06-09 11:43:38 +0000 (Wed, 09 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/ClassLoader.py Modified: trunk/pyscard/src/smartcard/ClassLoader.py =================================================================== --- trunk/pyscard/src/smartcard/ClassLoader.py 2010-06-09 11:43:03 UTC (rev 454) +++ trunk/pyscard/src/smartcard/ClassLoader.py 2010-06-09 11:43:38 UTC (rev 455) @@ -10,10 +10,12 @@ import sys import types + def get_mod(modulePath): """Import a module.""" return __import__(modulePath, globals(), locals(), ['']) + def get_func(fullFuncName): """Retrieve a function object from a full dotted-package name.""" @@ -32,6 +34,7 @@ # not the results of the function. return aFunc + def get_class(fullClassName, parentClass=None): """Load a module and retrieve a class (NOT an instance). This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-09 11:43:09
|
Revision: 454 http://pyscard.svn.sourceforge.net/pyscard/?rev=454&view=rev Author: ludov Date: 2010-06-09 11:43:03 +0000 (Wed, 09 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/CardType.py Modified: trunk/pyscard/src/smartcard/CardType.py =================================================================== --- trunk/pyscard/src/smartcard/CardType.py 2010-06-09 11:40:50 UTC (rev 453) +++ trunk/pyscard/src/smartcard/CardType.py 2010-06-09 11:43:03 UTC (rev 454) @@ -25,23 +25,23 @@ from smartcard.util import toHexString -class CardType: +class CardType: """Abstract base class for CardTypes. Known sub-classes: smartcard.CardType.AnyCardType smartcard.CardType.ATRCardType.""" - def __init__( self ): + def __init__(self): """CardType constructor.""" pass - def matches( self, atr, reader=None ): + def matches(self, atr, reader=None): """Returns true if atr and card connected match the CardType. atr: the atr to chek for matching reader: the reader (optional); default is None - - The reader can be use in some sub-classes to do advanced + + The reader can be use in some sub-classes to do advanced matching that require connecting to the card.""" pass @@ -49,7 +49,7 @@ class AnyCardType(CardType): """The AnyCardType matches any card.""" - def matches( self, atr, reader=None ): + def matches(self, atr, reader=None): """Always returns true, i.e. AnyCardType matches any card. atr: the atr to chek for matching @@ -60,46 +60,46 @@ class ATRCardType(CardType): """The ATRCardType defines a card from an ATR and a mask.""" - def __init__( self, atr, mask=None ): + def __init__(self, atr, mask=None): """ATRCardType constructor. atr: the ATR of the CardType mask: an optional mask to be applied to the ATR for CardType matching default is None """ - self.atr=list(atr) - self.mask=mask - if None==mask: - self.maskedatr=self.atr + self.atr = list(atr) + self.mask = mask + if None == mask: + self.maskedatr = self.atr else: - if len(self.atr)!=len(self.mask): - raise InvalidATRMaskLengthException( toHexString(mask) ) - self.maskedatr=map( lambda x, y: x & y, self.atr, self.mask ) + if len(self.atr) != len(self.mask): + raise InvalidATRMaskLengthException(toHexString(mask)) + self.maskedatr = map(lambda x, y: x & y, self.atr, self.mask) - def matches( self, atr, reader=None ): + def matches(self, atr, reader=None): """Returns true if the atr matches the masked CardType atr. - + atr: the atr to chek for matching reader: the reader (optional); default is None When atr is compared to the CardType ATR, matches returns true if - and only if CardType.atr & CardType.mask = atr & CardType.mask, + and only if CardType.atr & CardType.mask = atr & CardType.mask, where & is the bitwise logical AND.""" - if len(atr)!=len(self.atr): + if len(atr) != len(self.atr): return not True - - if None!=self.mask: - maskedatr=map( lambda x, y: x & y, list(atr), self.mask ) + + if None != self.mask: + maskedatr = map(lambda x, y: x & y, list(atr), self.mask) else: - maskedatr=atr - return self.maskedatr==maskedatr + maskedatr = atr + return self.maskedatr == maskedatr - + if __name__ == '__main__': """Small sample illustrating the use of CardType.py.""" - r=readers() + r = readers() print r connection = r[0].createConnection() connection.connect() - atrct=ATRCardType( [0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00, 0x0D] ) - print atrct.matches( connection.getATR() ) + atrct = ATRCardType([0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00, 0x0D]) + print atrct.matches(connection.getATR()) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-09 11:41:00
|
Revision: 453 http://pyscard.svn.sourceforge.net/pyscard/?rev=453&view=rev Author: ludov Date: 2010-06-09 11:40:50 +0000 (Wed, 09 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/CardService.py Modified: trunk/pyscard/src/smartcard/CardService.py =================================================================== --- trunk/pyscard/src/smartcard/CardService.py 2010-06-09 11:40:18 UTC (rev 452) +++ trunk/pyscard/src/smartcard/CardService.py 2010-06-09 11:40:50 UTC (rev 453) @@ -39,7 +39,7 @@ Known subclasses: smartcard.PassThruCardService """ - def __init__( self, connection, cardname=None ): + def __init__(self, connection, cardname=None): """Construct a new card service and bind to a smart card in a reader. connection: the CardConnection used to access the smart card @@ -47,13 +47,13 @@ self.connection = connection self.cardname = cardname - def __del__( self ): + def __del__(self): """Destructor. Disconnect card and destroy card service resources.""" self.connection.disconnect() - def supports( cardname ): + def supports(cardname): pass - supports = staticmethod( supports ) + supports = staticmethod(supports) if __name__ == '__main__': @@ -62,8 +62,8 @@ DF_TELECOM = [0x7F, 0x10] from smartcard.System import readers cc = readers()[0].createConnection() - cs = CardService( cc ) + cs = CardService(cc) cs.connection.connect() - data, sw1, sw2 = cs.connection.transmit( SELECT + DF_TELECOM ) - print "%X %X" % ( sw1, sw2 ) + data, sw1, sw2 = cs.connection.transmit(SELECT + DF_TELECOM) + print "%X %X" % (sw1, sw2) cs.connection.disconnect() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-09 11:40:28
|
Revision: 452 http://pyscard.svn.sourceforge.net/pyscard/?rev=452&view=rev Author: ludov Date: 2010-06-09 11:40:18 +0000 (Wed, 09 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/CardRequest.py Modified: trunk/pyscard/src/smartcard/CardRequest.py =================================================================== --- trunk/pyscard/src/smartcard/CardRequest.py 2010-06-09 11:37:39 UTC (rev 451) +++ trunk/pyscard/src/smartcard/CardRequest.py 2010-06-09 11:40:18 UTC (rev 452) @@ -24,43 +24,49 @@ from smartcard.pcsc.PCSCCardRequest import PCSCCardRequest + class CardRequest: """A CardRequest is used for waitForCard() invocations and specifies what kind of smart card an application is waited for. """ - def __init__( self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1 ): + def __init__(self, newcardonly=False, readers=None, cardType=None, + cardServiceClass=None, timeout=1): """Construct new CardRequest. newcardonly: if True, request a new card - default is False, i.e. accepts cards already inserted + default is False, i.e. accepts cards already + inserted - readers: the list of readers to consider for requesting a card - default is to consider all readers + readers: the list of readers to consider for + requesting a card default is to consider all + readers - cardType: the smartcard.CardType.CardType to wait for; default is - smartcard.CardType.AnyCardType, i.e. the request will - succeed with any card + cardType: the smartcard.CardType.CardType to wait for; + default is smartcard.CardType.AnyCardType, + i.e. the request will succeed with any card - cardServiceClass: the specific card service class to create and bind to the card - default is to create and bind a smartcard.PassThruCardService + cardServiceClass: the specific card service class to create + and bind to the card default is to create + and bind a smartcard.PassThruCardService - timeout: the time in seconds we are ready to wait for connecting to the - requested card. - default is to wait one second - to wait forever, set timeout to None + timeout: the time in seconds we are ready to wait for + connecting to the requested card. default + is to wait one second to wait forever, set + timeout to None """ - self.pcsccardrequest=PCSCCardRequest( newcardonly, readers, cardType, cardServiceClass, timeout ) + self.pcsccardrequest = PCSCCardRequest(newcardonly, readers, + cardType, cardServiceClass, timeout) - def getReaders( self ): + def getReaders(self): """Returns the list or readers on which to wait for cards.""" return self.pcsccardrequest.getReaders() - def waitforcard( self ): + def waitforcard(self): """Wait for card insertion and returns a card service.""" return self.pcsccardrequest.waitforcard() - def waitforcardevent( self ): + def waitforcardevent(self): """Wait for card insertion or removal.""" return self.pcsccardrequest.waitforcardevent() @@ -70,7 +76,7 @@ from smartcard.util import toHexString print 'Insert a new card within 10 seconds' - cr=CardRequest( timeout=10, newcardonly=True ) + cr = CardRequest(timeout=10, newcardonly=True) cs = cr.waitforcard() cs.connection.connect() print cs.connection.getReader(), toHexString(cs.connection.getATR()) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-09 11:37:45
|
Revision: 451 http://pyscard.svn.sourceforge.net/pyscard/?rev=451&view=rev Author: ludov Date: 2010-06-09 11:37:39 +0000 (Wed, 09 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/CardNames.py Modified: trunk/pyscard/src/smartcard/CardNames.py =================================================================== --- trunk/pyscard/src/smartcard/CardNames.py 2010-06-09 08:02:58 UTC (rev 450) +++ trunk/pyscard/src/smartcard/CardNames.py 2010-06-09 11:37:39 UTC (rev 451) @@ -31,76 +31,79 @@ from smartcard.Synchronization import Synchronization, synchronize from smartcard.util import toBytes -class __CardNames__(Synchronization): + +class __CardNames__(Synchronization): """__CardNames__ inner class. Stores card names and card types into a bsddb hash database. - The smartcard.CardNames.CardNames singleton manages the creation + The smartcard.CardNames.CardNames singleton manages the creation of the unique instance of this class. """ - def __init__( self ): + def __init__(self): Synchronization.__init__(self) - carddb_dir=environ['ALLUSERSPROFILE'] - carddb_file='cardnames.bdb' - carddb_file=join( carddb_dir, carddb_file ) - self.db=hashopen( carddb_file, 'w' ) - + carddb_dir = environ['ALLUSERSPROFILE'] + carddb_file = 'cardnames.bdb' + carddb_file = join(carddb_dir, carddb_file) + self.db = hashopen(carddb_file, 'w') + def __del__(self): self.db.sync() self.db.close() - def add( self, cardname, cardtype ): - self.db[cardname]=dumps(cardtype, HIGHEST_PROTOCOL ) + def add(self, cardname, cardtype): + self.db[cardname] = dumps(cardtype, HIGHEST_PROTOCOL) self.db.sync() - def delete( self, cardname ): + def delete(self, cardname): try: del self.db[cardname] except DBNotFoundError: pass - def dump( self ): + def dump(self): for k, v in self.db.iteritems(): print k, `loads(v)` - def find( self, atr, reader=None ): + def find(self, atr, reader=None): for k, v in self.db.iteritems(): - if loads(v).matches( atr, reader ): + if loads(v).matches(atr, reader): return k - -synchronize( __CardNames__, "add delete dump find" ) +synchronize(__CardNames__, "add delete dump find") + class CardNames: - """The CardNames organizes cards by a unique name and an associated smartcard.CardType.CardType.""" + """The CardNames organizes cards by a unique name and an associated + smartcard.CardType.CardType.""" """The single instance of __CardNames__""" instance = None - """Constructor: create a single instance of __readergroups on first call""" - def __init__(self ): - if None==CardNames.instance: + def __init__(self): + """Constructor: create a single instance of __readergroups on + first call""" + if None == CardNames.instance: CardNames.instance = __CardNames__() - """All operators redirected to inner class.""" def __getattr__(self, name): + """All operators redirected to inner class.""" return getattr(self.instance, name) if __name__ == '__main__': from smartcard.CardType import ATRCardType - + # define a card by its ATR - ct = ATRCardType( [0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00, 0x0D] ) - + ct = ATRCardType([0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00, 0x0D]) + # create CardName - cn=CardNames() - cn.add( "Palmera Protect V2", ct ) + cn = CardNames() + cn.add("Palmera Protect V2", ct) cn.dump() - print cn.find( [0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00, 0x0D] ) - print cn.find( [0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00] ) - cn.delete( "Palmera Protect V2" ) + print cn.find([0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00, 0x0D]) + print cn.find([0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00]) + cn.delete("Palmera Protect V2") print '---------' cn.dump() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-09 08:03:07
|
Revision: 450 http://pyscard.svn.sourceforge.net/pyscard/?rev=450&view=rev Author: ludov Date: 2010-06-09 08:02:58 +0000 (Wed, 09 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/CardConnectionEvent.py trunk/pyscard/src/smartcard/CardMonitoring.py Modified: trunk/pyscard/src/smartcard/CardConnectionEvent.py =================================================================== --- trunk/pyscard/src/smartcard/CardConnectionEvent.py 2010-06-09 07:55:12 UTC (rev 449) +++ trunk/pyscard/src/smartcard/CardConnectionEvent.py 2010-06-09 08:02:58 UTC (rev 450) @@ -23,6 +23,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ + class CardConnectionEvent: """Base class for card connection events. @@ -33,6 +34,7 @@ command APDU byte list for 'command' [response data, sw1, sw2] for 'response' type: 'connect' args:""" - def __init__( self, type, args=None): - self.type=type - self.args=args + + def __init__(self, type, args=None): + self.type = type + self.args = args Modified: trunk/pyscard/src/smartcard/CardMonitoring.py =================================================================== --- trunk/pyscard/src/smartcard/CardMonitoring.py 2010-06-09 07:55:12 UTC (rev 449) +++ trunk/pyscard/src/smartcard/CardMonitoring.py 2010-06-09 08:02:58 UTC (rev 450) @@ -40,17 +40,20 @@ from smartcard.CardType import AnyCardType from smartcard.CardRequest import CardRequest -_START_ON_DEMAND_=False +_START_ON_DEMAND_ = False + # CardObserver interface class CardObserver(Observer): """ CardObserver is a base abstract class for objects that are to be notified upon smartcard reader insertion/removal. """ + def __init__(self): pass - def update( self, observable, (addedcards, removedcards) ): + + def update(self, observable, (addedcards, removedcards)): """Called upon reader insertion/removal. observable: @@ -59,6 +62,7 @@ """ pass + class CardMonitor: """Class that monitors smart card insertion/removal. and notify observers @@ -73,45 +77,46 @@ there is only one CardMonitor. """ - class __CardMonitorSingleton( Observable ): + class __CardMonitorSingleton(Observable): """The real smartcard monitor class. A single instance of this class is created by the public CardMonitor class. """ - def __init__( self ): + + def __init__(self): Observable.__init__(self) if _START_ON_DEMAND_: - self.rmthread=None + self.rmthread = None else: - self.rmthread = CardMonitoringThread( self ) + self.rmthread = CardMonitoringThread(self) - def addObserver( self, observer ): + def addObserver(self, observer): """Add an observer. We only start the card monitoring thread when there are observers. """ - Observable.addObserver( self, observer ) + Observable.addObserver(self, observer) if _START_ON_DEMAND_: - if self.countObservers()>0 and self.rmthread==None: - self.rmthread = CardMonitoringThread( self ) + if self.countObservers() > 0 and self.rmthread == None: + self.rmthread = CardMonitoringThread(self) else: - observer.update( self, (self.rmthread.cards, [] ) ) + observer.update(self, (self.rmthread.cards, [])) - def deleteObserver( self, observer ): + def deleteObserver(self, observer): """Remove an observer. We delete the CardMonitoringThread reference when there are no more observers. """ - Observable.deleteObserver( self, observer ) + Observable.deleteObserver(self, observer) if _START_ON_DEMAND_: - if self.countObservers()==0: - if self.rmthread!=None: - self.rmthread=None + if self.countObservers() == 0: + if self.rmthread != None: + self.rmthread = None - def __str__( self ): + def __str__(self): return 'CardMonitor' # the singleton @@ -121,8 +126,8 @@ if not CardMonitor.instance: CardMonitor.instance = CardMonitor.__CardMonitorSingleton() - def __getattr__( self, name ): - return getattr( self.instance, name ) + def __getattr__(self, name): + return getattr(self.instance, name) class CardMonitoringThread: @@ -130,15 +135,16 @@ This thread waits for card insertion. """ - class __CardMonitoringThreadSingleton( Thread ): + class __CardMonitoringThreadSingleton(Thread): """The real card monitoring thread class. A single instance of this class is created by the public CardMonitoringThread class. """ + def __init__(self, observable): Thread.__init__(self) - self.observable=observable + self.observable = observable self.stopEvent = Event() self.stopEvent.clear() self.cards = [] @@ -149,31 +155,32 @@ """Runs until stopEvent is notified, and notify observers of all card insertion/removal. """ - self.cardrequest = CardRequest( timeout=0.1 ) - while self.stopEvent.isSet()!=1: + self.cardrequest = CardRequest(timeout=0.1) + while self.stopEvent.isSet() != 1: try: currentcards = self.cardrequest.waitforcardevent() - addedcards=[] + addedcards = [] for card in currentcards: - if not self.cards.__contains__( card ): - addedcards.append( card ) + if not self.cards.__contains__(card): + addedcards.append(card) - removedcards=[] + removedcards = [] for card in self.cards: - if not currentcards.__contains__( card ): - removedcards.append( card ) + if not currentcards.__contains__(card): + removedcards.append(card) - if addedcards!=[] or removedcards!=[]: - self.cards=currentcards + if addedcards != [] or removedcards != []: + self.cards = currentcards self.observable.setChanged() - self.observable.notifyObservers( (addedcards, removedcards) ) + self.observable.notifyObservers((addedcards, removedcards)) - # when CardMonitoringThread.__del__() is invoked in response to shutdown, - # e.g., when execution of the program is done, other globals referenced - # by the __del__() method may already have been deleted. - # this causes ReaderMonitoringThread.run() to except with a TypeError - # or AttributeError + # when CardMonitoringThread.__del__() is invoked in + # response to shutdown, e.g., when execution of the + # program is done, other globals referenced by the + # __del__() method may already have been deleted. + # this causes ReaderMonitoringThread.run() to except + # with a TypeError or AttributeError except TypeError: pass except AttributeError: @@ -197,16 +204,15 @@ def __init__(self, observable): if not CardMonitoringThread.instance: - CardMonitoringThread.instance = CardMonitoringThread.__CardMonitoringThreadSingleton( observable ) + CardMonitoringThread.instance = CardMonitoringThread.__CardMonitoringThreadSingleton(observable) CardMonitoringThread.instance.start() - - def __getattr__( self, name ): + def __getattr__(self, name): if self.instance: - return getattr( self.instance, name ) + return getattr(self.instance, name) - # commented to avoid bad clean-up sequence of python where __del__ is called when - # some objects it uses are already gargabe collected + # commented to avoid bad clean-up sequence of python where __del__ + # is called when some objects it uses are already gargabe collected #def __del__(self): # if CardMonitoringThread.instance!=None: # CardMonitoringThread.instance.stop() @@ -218,24 +224,26 @@ print 'insert or remove cards in the next 10 seconds' # a simple card observer that prints added/removed cards - class printobserver( CardObserver ): - def __init__( self, obsindex ): - self.obsindex=obsindex + class printobserver(CardObserver): - def update( self, observable, (addedcards, removedcards) ): + def __init__(self, obsindex): + self.obsindex = obsindex + + def update(self, observable, (addedcards, removedcards)): print "%d - added: " % self.obsindex, addedcards print "%d - removed: " % self.obsindex, removedcards - class testthread( Thread ): - def __init__(self, obsindex ): + class testthread(Thread): + + def __init__(self, obsindex): Thread.__init__(self) self.readermonitor = CardMonitor() self.obsindex = obsindex - self.observer=None + self.observer = None def run(self): # create and register observer - self.observer = printobserver( self.obsindex ) + self.observer = printobserver(self.obsindex) self.readermonitor.addObserver(self.observer) sleep(10) self.readermonitor.deleteObserver(self.observer) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-09 07:55:20
|
Revision: 449 http://pyscard.svn.sourceforge.net/pyscard/?rev=449&view=rev Author: ludov Date: 2010-06-09 07:55:12 +0000 (Wed, 09 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/CardConnectionDecorator.py Modified: trunk/pyscard/src/smartcard/CardConnectionDecorator.py =================================================================== --- trunk/pyscard/src/smartcard/CardConnectionDecorator.py 2010-06-09 07:54:18 UTC (rev 448) +++ trunk/pyscard/src/smartcard/CardConnectionDecorator.py 2010-06-09 07:55:12 UTC (rev 449) @@ -1,6 +1,6 @@ -"""The CardConnectionDecorator is a Decorator around the CardConnection abstract class, -and allows dynamic addition of features to the CardConnection, e.g. implementing a -secure channel.. +"""The CardConnectionDecorator is a Decorator around the CardConnection +abstract class, and allows dynamic addition of features to the +CardConnection, e.g. implementing a secure channel.. __author__ = "http://www.gemalto.com" @@ -26,60 +26,61 @@ from smartcard.CardConnection import CardConnection -class CardConnectionDecorator( CardConnection ): + +class CardConnectionDecorator(CardConnection): """Card connection decorator class.""" - def __init__( self, cardConnectionComponent ): + def __init__(self, cardConnectionComponent): """Construct a new card connection decorator. CardConnectionComponent: CardConnection component to decorate """ self.component = cardConnectionComponent - def addSWExceptionToFilter( self, exClass ): + def addSWExceptionToFilter(self, exClass): """call inner component addSWExceptionToFilter""" - self.component.addSWExceptionToFilter( exClass ) + self.component.addSWExceptionToFilter(exClass) def addObserver(self, observer): """call inner component addObserver""" - self.component.addObserver( observer ) + self.component.addObserver(observer) def deleteObserver(self, observer): """call inner component deleteObserver""" - self.component.deleteObserver( observer ) + self.component.deleteObserver(observer) - def connect( self, protocol=None, mode=None, disposition=None ): + def connect(self, protocol=None, mode=None, disposition=None): """call inner component connect""" - self.component.connect( protocol, mode, disposition ) + self.component.connect(protocol, mode, disposition) - def disconnect( self ): + def disconnect(self): """call inner component disconnect""" self.component.disconnect() - def getATR( self ): + def getATR(self): """call inner component getATR""" return self.component.getATR() - def getProtocol( self ): + def getProtocol(self): """call inner component getProtocol""" return self.component.getProtocol() - def getReader( self ): + def getReader(self): """call inner component getReader""" return self.component.getReader() - def setErrorCheckingChain( self, errorcheckingchain ): + def setErrorCheckingChain(self, errorcheckingchain): """call inner component setErrorCheckingChain""" - self.component.setErrorCheckingChain( errorcheckingchain ) + self.component.setErrorCheckingChain(errorcheckingchain) - def setProtocol( self, protocol ): + def setProtocol(self, protocol): """call inner component setProtocol""" - return self.component.setProtocol( protocol ) + return self.component.setProtocol(protocol) - def transmit( self, bytes, protocol=None ): + def transmit(self, bytes, protocol=None): """call inner component transmit""" - return self.component.transmit( bytes, protocol ) + return self.component.transmit(bytes, protocol) - def control( self, controlCode, bytes=[] ): + def control(self, controlCode, bytes=[]): """call inner component control""" - return self.component.control( controlCode, bytes ) + return self.component.control(controlCode, bytes) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-09 07:54:25
|
Revision: 448 http://pyscard.svn.sourceforge.net/pyscard/?rev=448&view=rev Author: ludov Date: 2010-06-09 07:54:18 +0000 (Wed, 09 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/CardConnection.py Modified: trunk/pyscard/src/smartcard/CardConnection.py =================================================================== --- trunk/pyscard/src/smartcard/CardConnection.py 2010-06-08 16:08:09 UTC (rev 447) +++ trunk/pyscard/src/smartcard/CardConnection.py 2010-06-09 07:54:18 UTC (rev 448) @@ -1,4 +1,5 @@ -"""The CardConnection abstract class manages connections with a card and apdu transmission. +"""The CardConnection abstract class manages connections with a card and +apdu transmission. __author__ = "http://www.gemalto.com" @@ -27,6 +28,7 @@ from smartcard.Observer import Observer from smartcard.Observer import Observable + class CardConnection(Observable): """Card connection abstract class. @@ -37,129 +39,137 @@ RAW_protocol = 0x00010000 T15_protocol = 0x00000008 - - def __init__( self, reader ): + def __init__(self, reader): """Construct a new card connection. - readerName: name of the reader in which the smartcard to connect to is located. + readerName: name of the reader in which the smartcard to connect + to is located. """ Observable.__init__(self) self.reader = reader - self.errorcheckingchain=None + self.errorcheckingchain = None self.defaultprotocol = CardConnection.T0_protocol | CardConnection.T1_protocol - def __del__( self ): + def __del__(self): """Connect to card.""" pass - def addSWExceptionToFilter( self, exClass ): + def addSWExceptionToFilter(self, exClass): """Add a status word exception class to be filtered. - exClass: the class to filter, e.g. smartcard.sw.SWException.WarningProcessingException + exClass: the class to filter, e.g. + smartcard.sw.SWException.WarningProcessingException Filtered exceptions will not be raised when encountered in the error checking chain.""" - if None!=self.errorcheckingchain: - self.errorcheckingchain[0].addFilterException( exClass ) + if None != self.errorcheckingchain: + self.errorcheckingchain[0].addFilterException(exClass) def addObserver(self, observer): """Add a CardConnection observer.""" - Observable.addObserver( self, observer ) + Observable.addObserver(self, observer) def deleteObserver(self, observer): """Remove a CardConnection observer.""" - Observable.deleteObserver( self, observer ) + Observable.deleteObserver(self, observer) - def connect( self, protocol=None, mode=None, disposition=None ): + def connect(self, protocol=None, mode=None, disposition=None): """Connect to card. - protocol: a bit mask of the protocols to use, from CardConnection.T0_protocol, CardConnection.T1_protocol, + protocol: a bit mask of the protocols to use, from + CardConnection.T0_protocol, CardConnection.T1_protocol, CardConnection.RAW_protocol, CardConnection.T15_protocol mode: passed as-is to the PC/SC layer """ - Observable.setChanged( self ) - Observable.notifyObservers( self, CardConnectionEvent('connect') ) + Observable.setChanged(self) + Observable.notifyObservers(self, CardConnectionEvent('connect')) - def disconnect( self ): + def disconnect(self): """Disconnect from card.""" - Observable.setChanged( self ) - Observable.notifyObservers( self, CardConnectionEvent('disconnect') ) + Observable.setChanged(self) + Observable.notifyObservers(self, CardConnectionEvent('disconnect')) - def getATR( self ): + def getATR(self): """Return card ATR""" pass - def getProtocol( self ): - """Return bit mask for the protocol of connection, or None if no protocol set. - The return value is a bit mask of CardConnection.T0_protocol, CardConnection.T1_protocol, + def getProtocol(self): + """Return bit mask for the protocol of connection, or None if no + protocol set. The return value is a bit mask of + CardConnection.T0_protocol, CardConnection.T1_protocol, CardConnection.RAW_protocol, CardConnection.T15_protocol """ return self.defaultprotocol - def getReader( self ): + def getReader(self): """Return card connection reader""" return self.reader - def setErrorCheckingChain( self, errorcheckingchain ): + def setErrorCheckingChain(self, errorcheckingchain): """Add an error checking chain. - errorcheckingchain: a smartcard.sw.ErrorCheckingChain object - The error checking strategies in errorchecking chain will be tested - with each received response APDU, and a smartcard.sw.SWException.SWException - will be raised upon error.""" - self.errorcheckingchain=errorcheckingchain + errorcheckingchain: a smartcard.sw.ErrorCheckingChain object The + error checking strategies in errorchecking chain will be tested + with each received response APDU, and a + smartcard.sw.SWException.SWException will be raised upon + error.""" + self.errorcheckingchain = errorcheckingchain - def setProtocol( self, protocol ): + def setProtocol(self, protocol): """Set protocol for card connection. - protocol: a bit mask of CardConnection.T0_protocol, CardConnection.T1_protocol, - CardConnection.RAW_protocol, CardConnection.T15_protocol - e.g. setProtocol( CardConnection.T1_protocol | CardConnection.T0_protocol ) - """ + protocol: a bit mask of CardConnection.T0_protocol, + CardConnection.T1_protocol, CardConnection.RAW_protocol, + CardConnection.T15_protocol e.g. + setProtocol(CardConnection.T1_protocol | + CardConnection.T0_protocol) """ self.defaultprotocol = protocol - def transmit( self, bytes, protocol=None ): - """Transmit an apdu. Internally calls doTransmit() class method and notify observers - upon command/response APDU events. + def transmit(self, bytes, protocol=None): + """Transmit an apdu. Internally calls doTransmit() class method + and notify observers upon command/response APDU events. Subclasses must override the doTransmit() class method. bytes: list of bytes to transmit - protocol: the transmission protocol, from CardConnection.T0_protocol, CardConnection.T1_protocol, - or CardConnection.RAW_protocol + protocol: the transmission protocol, from + CardConnection.T0_protocol, + CardConnection.T1_protocol, or + CardConnection.RAW_protocol """ - Observable.setChanged( self ) - Observable.notifyObservers( self, CardConnectionEvent('command', [bytes, protocol] ) ) - data, sw1, sw2 = self.doTransmit( bytes, protocol ) - Observable.setChanged( self ) - Observable.notifyObservers( self, CardConnectionEvent( 'response', [data, sw1, sw2 ] ) ) - if None!=self.errorcheckingchain: - self.errorcheckingchain[0]( data, sw1, sw2 ) + Observable.setChanged(self) + Observable.notifyObservers(self, CardConnectionEvent('command', [bytes, protocol])) + data, sw1, sw2 = self.doTransmit(bytes, protocol) + Observable.setChanged(self) + Observable.notifyObservers(self, CardConnectionEvent('response', [data, sw1, sw2])) + if None != self.errorcheckingchain: + self.errorcheckingchain[0](data, sw1, sw2) return data, sw1, sw2 - def doTransmit( self, bytes, protocol ): + def doTransmit(self, bytes, protocol): """Performs the command APDU transmission. - Subclasses must override this method for implementing apdu transmission.""" + Subclasses must override this method for implementing apdu + transmission.""" pass - def control( self, controlCode, bytes=[] ): + def control(self, controlCode, bytes=[]): """Send a control command and buffer. Internally calls doControl() class method and notify observers upon command/response events. Subclasses must override the doControl() class method. controlCode: command code - + bytes: list of bytes to transmit """ - Observable.setChanged( self ) - Observable.notifyObservers( self, CardConnectionEvent('command', [controlCode, bytes] ) ) - data = self.doControl( controlCode, bytes ) - Observable.setChanged( self ) - Observable.notifyObservers( self, CardConnectionEvent( 'response', data ) ) - if None!=self.errorcheckingchain: - self.errorcheckingchain[0]( data ) + Observable.setChanged(self) + Observable.notifyObservers(self, CardConnectionEvent('command', [controlCode, bytes])) + data = self.doControl(controlCode, bytes) + Observable.setChanged(self) + Observable.notifyObservers(self, CardConnectionEvent('response', data)) + if None != self.errorcheckingchain: + self.errorcheckingchain[0](data) return data - def doControl( self, controlCode, bytes ): + def doControl(self, controlCode, bytes): """Performs the command control. Subclasses must override this method for implementing control.""" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jda...@us...> - 2010-06-08 16:08:16
|
Revision: 447 http://pyscard.svn.sourceforge.net/pyscard/?rev=447&view=rev Author: jdaussel Date: 2010-06-08 16:08:09 +0000 (Tue, 08 Jun 2010) Log Message: ----------- Make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py Modified: trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py =================================================================== --- trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py 2010-06-07 17:09:55 UTC (rev 446) +++ trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py 2010-06-08 16:08:09 UTC (rev 447) @@ -55,7 +55,8 @@ self.groupname = groupname def __str__(self): - return repr('Failure to add reader: ' + self.readername + ' to group: ' + self.groupname + ' ' + + return repr('Failure to add reader: ' + self.readername + + ' to group: ' + self.groupname + ' ' + smartcard.scard.SCardGetErrorMessage(self.hresult)) @@ -84,8 +85,8 @@ self.readername = readername def __str__(self): - return repr('Failure to introduce a new reader: ' + self.readername + ' ' + - smartcard.scard.SCardGetErrorMessage(self.hresult)) + return repr('Failure to introduce a new reader: ' + self.readername + + ' ' + smartcard.scard.SCardGetErrorMessage(self.hresult)) class ReleaseContextException(BaseSCardException): @@ -105,7 +106,8 @@ self.groupname = groupname def __str__(self): - return repr('Failure to remove reader: ' + self.readername + ' from group: ' + self.groupname + ' ' + + return repr('Failure to remove reader: ' + self.readername + + ' from group: ' + self.groupname + ' ' + smartcard.scard.SCardGetErrorMessage(self.hresult)) if __name__ == "__main__": This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-07 17:10:01
|
Revision: 446 http://pyscard.svn.sourceforge.net/pyscard/?rev=446&view=rev Author: ludov Date: 2010-06-07 17:09:55 +0000 (Mon, 07 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py trunk/pyscard/src/smartcard/pcsc/PCSCReader.py Modified: trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py =================================================================== --- trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py 2010-06-07 17:04:20 UTC (rev 445) +++ trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py 2010-06-07 17:09:55 UTC (rev 446) @@ -49,8 +49,8 @@ class AddReaderToGroupException(BaseSCardException): """Raised when scard fails to add a new reader to a PCSC reader group.""" - def __init__( self, hresult, readername="", groupname="" ): - BaseSCardException.__init__( self, hresult ) + def __init__(self, hresult, readername="", groupname=""): + BaseSCardException.__init__(self, hresult) self.readername = readername self.groupname = groupname @@ -58,6 +58,7 @@ return repr('Failure to add reader: ' + self.readername + ' to group: ' + self.groupname + ' ' + smartcard.scard.SCardGetErrorMessage(self.hresult)) + class EstablishContextException(BaseSCardException): """Raised when scard failed to establish context with PCSC.""" @@ -78,8 +79,8 @@ class IntroduceReaderException(BaseSCardException): """Raised when scard fails to introduce a new reader to PCSC.""" - def __init__( self, hresult, readername="" ): - BaseSCardException.__init__( self, hresult ) + def __init__(self, hresult, readername=""): + BaseSCardException.__init__(self, hresult) self.readername = readername def __str__(self): @@ -94,11 +95,12 @@ return repr('Failure to release context: ' + smartcard.scard.SCardGetErrorMessage(self.hresult)) + class RemoveReaderFromGroupException(BaseSCardException): """Raised when scard fails to remove a reader from a PCSC reader group.""" - def __init__( self, hresult, readername="", groupname="" ): - BaseSCardException.__init__( self, hresult ) + def __init__(self, hresult, readername="", groupname=""): + BaseSCardException.__init__(self, hresult) self.readername = readername self.groupname = groupname Modified: trunk/pyscard/src/smartcard/pcsc/PCSCReader.py =================================================================== --- trunk/pyscard/src/smartcard/pcsc/PCSCReader.py 2010-06-07 17:04:20 UTC (rev 445) +++ trunk/pyscard/src/smartcard/pcsc/PCSCReader.py 2010-06-07 17:09:55 UTC (rev 446) @@ -67,10 +67,10 @@ try: hresult = SCardIntroduceReader(hcontext, self.name, self.name) if 0 != hresult and SCARD_E_DUPLICATE_READER != hresult: - raise IntroduceReaderException(hresult,self.name) + raise IntroduceReaderException(hresult, self.name) hresult = SCardAddReaderToGroup(hcontext, self.name, groupname) if 0 != hresult: - raise AddReaderToGroupException(hresult,self.name,groupname) + raise AddReaderToGroupException(hresult, self.name, groupname) finally: hresult = SCardReleaseContext(hcontext) if 0 != hresult: @@ -85,7 +85,7 @@ try: hresult = SCardRemoveReaderFromGroup(hcontext, self.name, groupname) if 0 != hresult: - raise RemoveReaderFromGroupException(hresult,self.name,groupname) + raise RemoveReaderFromGroupException(hresult, self.name, groupname) finally: hresult = SCardReleaseContext(hcontext) if 0 != hresult: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jda...@us...> - 2010-06-07 17:04:28
|
Revision: 445 http://pyscard.svn.sourceforge.net/pyscard/?rev=445&view=rev Author: jdaussel Date: 2010-06-07 17:04:20 +0000 (Mon, 07 Jun 2010) Log Message: ----------- Added three new exceptions Modified Paths: -------------- trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py trunk/pyscard/src/smartcard/pcsc/PCSCReader.py Modified: trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py =================================================================== --- trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py 2010-06-06 18:53:08 UTC (rev 444) +++ trunk/pyscard/src/smartcard/pcsc/PCSCExceptions.py 2010-06-07 17:04:20 UTC (rev 445) @@ -46,6 +46,18 @@ smartcard.scard.SCardGetErrorMessage(self.hresult)) +class AddReaderToGroupException(BaseSCardException): + """Raised when scard fails to add a new reader to a PCSC reader group.""" + + def __init__( self, hresult, readername="", groupname="" ): + BaseSCardException.__init__( self, hresult ) + self.readername = readername + self.groupname = groupname + + def __str__(self): + return repr('Failure to add reader: ' + self.readername + ' to group: ' + self.groupname + ' ' + + smartcard.scard.SCardGetErrorMessage(self.hresult)) + class EstablishContextException(BaseSCardException): """Raised when scard failed to establish context with PCSC.""" @@ -63,11 +75,15 @@ smartcard.scard.SCardGetErrorMessage(self.hresult)) -class EstablishContextException(BaseSCardException): - """Raised when scard failed to establish a PCSC context.""" +class IntroduceReaderException(BaseSCardException): + """Raised when scard fails to introduce a new reader to PCSC.""" + def __init__( self, hresult, readername="" ): + BaseSCardException.__init__( self, hresult ) + self.readername = readername + def __str__(self): - return repr('Failure to establish context: ' + + return repr('Failure to introduce a new reader: ' + self.readername + ' ' + smartcard.scard.SCardGetErrorMessage(self.hresult)) @@ -78,6 +94,18 @@ return repr('Failure to release context: ' + smartcard.scard.SCardGetErrorMessage(self.hresult)) +class RemoveReaderFromGroupException(BaseSCardException): + """Raised when scard fails to remove a reader from a PCSC reader group.""" + + def __init__( self, hresult, readername="", groupname="" ): + BaseSCardException.__init__( self, hresult ) + self.readername = readername + self.groupname = groupname + + def __str__(self): + return repr('Failure to remove reader: ' + self.readername + ' from group: ' + self.groupname + ' ' + + smartcard.scard.SCardGetErrorMessage(self.hresult)) + if __name__ == "__main__": import sys try: Modified: trunk/pyscard/src/smartcard/pcsc/PCSCReader.py =================================================================== --- trunk/pyscard/src/smartcard/pcsc/PCSCReader.py 2010-06-06 18:53:08 UTC (rev 444) +++ trunk/pyscard/src/smartcard/pcsc/PCSCReader.py 2010-06-07 17:04:20 UTC (rev 445) @@ -67,10 +67,10 @@ try: hresult = SCardIntroduceReader(hcontext, self.name, self.name) if 0 != hresult and SCARD_E_DUPLICATE_READER != hresult: - raise error, 'Unable to introduce reader: ' + self.name + ' : ' + SCardGetErrorMessage(hresult) + raise IntroduceReaderException(hresult,self.name) hresult = SCardAddReaderToGroup(hcontext, self.name, groupname) if 0 != hresult: - raise error, 'Unable to add reader to group: ' + SCardGetErrorMessage(hresult) + raise AddReaderToGroupException(hresult,self.name,groupname) finally: hresult = SCardReleaseContext(hcontext) if 0 != hresult: @@ -85,7 +85,7 @@ try: hresult = SCardRemoveReaderFromGroup(hcontext, self.name, groupname) if 0 != hresult: - raise error, 'Unable to add reader to group: ' + SCardGetErrorMessage(hresult) + raise RemoveReaderFromGroupException(hresult,self.name,groupname) finally: hresult = SCardReleaseContext(hcontext) if 0 != hresult: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 18:53:14
|
Revision: 444 http://pyscard.svn.sourceforge.net/pyscard/?rev=444&view=rev Author: ludov Date: 2010-06-06 18:53:08 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/Card.py Modified: trunk/pyscard/src/smartcard/Card.py =================================================================== --- trunk/pyscard/src/smartcard/Card.py 2010-06-06 18:49:05 UTC (rev 443) +++ trunk/pyscard/src/smartcard/Card.py 2010-06-06 18:53:08 UTC (rev 444) @@ -26,45 +26,47 @@ from smartcard.System import readers from smartcard.util import toHexString + class Card: """Card class.""" - def __init__( self, reader, atr ): + + def __init__(self, reader, atr): """Card constructor. reader: reader in which the card is inserted atr: ATR of the card""" - self.reader=reader - self.atr=atr + self.reader = reader + self.atr = atr - def __repr__( self ): - """Return a string representing the Card (atr and reader concatenation).""" - return toHexString( self.atr ) + ' / ' + str(self.reader) + def __repr__(self): + """Return a string representing the Card (atr and reader + concatenation).""" + return toHexString(self.atr) + ' / ' + str(self.reader) - - def __eq__( self, other ): + def __eq__(self, other): """Return True if self==other (same reader and same atr). Return False otherwise.""" - if isinstance( other, Card ): - return (self.atr==other.atr and `self.reader`==`other.reader`) + if isinstance(other, Card): + return (self.atr == other.atr and `self.reader` == `other.reader`) else: return False - def __ne__( self, other ): - """Return True if self!=other (same reader and same atr).Returns False otherwise.""" - return not self.__eq__( other ) + def __ne__(self, other): + """Return True if self!=other (same reader and same atr).Returns + False otherwise.""" + return not self.__eq__(other) - - def createConnection( self ): + def createConnection(self): """Return a CardConnection to the Card object.""" - readerobj=None - if isinstance( self.reader, Reader ): - readerobj=self.reader - elif type(self.reader)==str: + readerobj = None + if isinstance(self.reader, Reader): + readerobj = self.reader + elif type(self.reader) == str: for reader in readers(): - if self.reader==str(reader): + if self.reader == str(reader): readerobj = reader if readerobj: return readerobj.createConnection() else: - #raise CardConnectionException( 'not a valid reader: ' + str(self.reader) ) + #raise CardConnectionException('not a valid reader: ' + str(self.reader)) return None This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 18:49:11
|
Revision: 443 http://pyscard.svn.sourceforge.net/pyscard/?rev=443&view=rev Author: ludov Date: 2010-06-06 18:49:05 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/ATR.py Modified: trunk/pyscard/src/smartcard/ATR.py =================================================================== --- trunk/pyscard/src/smartcard/ATR.py 2010-06-06 18:42:16 UTC (rev 442) +++ trunk/pyscard/src/smartcard/ATR.py 2010-06-06 18:49:05 UTC (rev 443) @@ -22,25 +22,25 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ + class ATR: + """ATR class.""" - clockrateconversion=[ 372, 372, 558, 744, 1116, 1488, 1860, 'RFU', 'RFU', 512, 768, 1024, 1536, 2048, 'RFU', 'RFU', 'RFU' ] - bitratefactor=['RFU', 1, 2, 4, 8, 16, 32, 'RFU', 12, 20, 'RFU', 'RFU', 'RFU', 'RFU', 'RFU', 'RFU' ] - currenttable=[ 25, 50, 100, 'RFU' ] + clockrateconversion = [372, 372, 558, 744, 1116, 1488, 1860, 'RFU', 'RFU', 512, 768, 1024, 1536, 2048, 'RFU', 'RFU', 'RFU'] + bitratefactor = ['RFU', 1, 2, 4, 8, 16, 32, 'RFU', 12, 20, 'RFU', 'RFU', 'RFU', 'RFU', 'RFU', 'RFU'] + currenttable = [25, 50, 100, 'RFU'] - - """ATR class.""" - def __init__( self, bytes ): + def __init__(self, bytes): """Construct a new atr from bytes.""" self.bytes = bytes self.__initInstance__() - def __checksyncbyte__( self ): + def __checksyncbyte__(self): """Check validity of TS.""" - if not 0x3b==self.bytes[0] and not 0x03f==self.bytes[0]: - raise 'invalid TS',"0x%-0.2x"%self.bytes[0] + if not 0x3b == self.bytes[0] and not 0x03f == self.bytes[0]: + raise 'invalid TS', "0x%-0.2x" % self.bytes[0] - def __initInstance__( self ): + def __initInstance__(self): """Parse ATR and initialize members: TS: initial character T0: format character @@ -76,18 +76,18 @@ self.hasTC = [] self.hasTD = [] - TD=self.T0 - hasTD=1 - n=0 - offset=1 - self.interfaceBytesCount=0 + TD = self.T0 + hasTD = 1 + n = 0 + offset = 1 + self.interfaceBytesCount = 0 while hasTD: - self.Y += [TD>>4 & 0x0f] + self.Y += [TD >> 4 & 0x0f] - self.hasTD += [(self.Y[n] & 0x08)!=0 ] - self.hasTC += [(self.Y[n] & 0x04)!=0 ] - self.hasTB += [(self.Y[n] & 0x02)!=0 ] - self.hasTA += [(self.Y[n] & 0x01)!=0 ] + self.hasTD += [(self.Y[n] & 0x08) != 0] + self.hasTC += [(self.Y[n] & 0x04) != 0] + self.hasTB += [(self.Y[n] & 0x02) != 0] + self.hasTA += [(self.Y[n] & 0x01) != 0] self.TA += [None] self.TB += [None] @@ -95,37 +95,37 @@ self.TD += [None] if self.hasTA[n]: - self.TA[n]=self.bytes[ offset+self.hasTA[n] ] + self.TA[n] = self.bytes[offset + self.hasTA[n]] if self.hasTB[n]: - self.TB[n]=self.bytes[ offset+self.hasTA[n]+self.hasTB[n] ] + self.TB[n] = self.bytes[offset + self.hasTA[n] + self.hasTB[n]] if self.hasTC[n]: - self.TC[n]=self.bytes[ offset+self.hasTA[n]+self.hasTB[n]+self.hasTC[n] ] + self.TC[n] = self.bytes[offset + self.hasTA[n] + self.hasTB[n] + self.hasTC[n]] if self.hasTD[n]: - self.TD[n]=self.bytes[ offset+self.hasTA[n]+self.hasTB[n]+self.hasTC[n]+self.hasTD[n] ] + self.TD[n] = self.bytes[offset + self.hasTA[n] + self.hasTB[n] + self.hasTC[n] + self.hasTD[n]] - self.interfaceBytesCount += self.hasTA[n]+self.hasTB[n]+self.hasTC[n]+self.hasTD[n] - TD=self.TD[n] - hasTD=self.hasTD[n] - offset=offset+self.hasTA[n]+self.hasTB[n]+self.hasTC[n]+self.hasTD[n] - n=n+1 + self.interfaceBytesCount += self.hasTA[n] + self.hasTB[n] + self.hasTC[n] + self.hasTD[n] + TD = self.TD[n] + hasTD = self.hasTD[n] + offset = offset + self.hasTA[n] + self.hasTB[n] + self.hasTC[n] + self.hasTD[n] + n = n + 1 # historical bytes - self.historicalBytes=self.bytes[offset+1:offset+1+self.K] + self.historicalBytes = self.bytes[offset + 1:offset + 1 + self.K] # checksum - self.hasChecksum = (len(self.bytes)==offset+1+self.K+1) + self.hasChecksum = (len(self.bytes) == offset + 1 + self.K + 1) if self.hasChecksum: - self.TCK=self.bytes[-1] - checksum=0 - for b in self.bytes[1:]: checksum = checksum ^ b - self.checksumOK = (checksum==0) + self.TCK = self.bytes[-1] + checksum = 0 + for b in self.bytes[1:]: + checksum = checksum ^ b + self.checksumOK = (checksum == 0) else: self.TCK = None - # clock-rate conversion factor if self.hasTA[0]: - self.FI = self.TA[0]>>4 & 0x0f + self.FI = self.TA[0] >> 4 & 0x0f else: self.FI = None @@ -137,7 +137,7 @@ # maximum programming current factor if self.hasTB[0]: - self.II = self.TB[0]>>5 & 0x03 + self.II = self.TB[0] >> 5 & 0x03 else: self.II = None @@ -150,32 +150,31 @@ # extra guard time self.N = self.TC[0] - - def getChecksum( self ): + def getChecksum(self): """Return the checksum of the ATR. Checksum is mandatory only for T=1.""" return self.TCK - def getHistoricalBytes( self ): + def getHistoricalBytes(self): """Return historical bytes.""" return self.historicalBytes - def getHistoricalBytesCount( self ): + def getHistoricalBytesCount(self): """Return count of historical bytes.""" - return len( self.historicalBytes ) + return len(self.historicalBytes) - def getInterfaceBytesCount( self ): + def getInterfaceBytesCount(self): """Return count of interface bytes.""" return self.interfaceBytesCount - def getTA1( self ): + def getTA1(self): """Return TA1 byte.""" return self.TA[0] - def getTB1( self ): + def getTB1(self): """Return TB1 byte.""" return self.TB[0] - def getTC1( self ): + def getTC1(self): """Return TC1 byte.""" return self.TC[0] @@ -183,76 +182,76 @@ """Return TD1 byte.""" return self.TD[0] - def getBitRateFactor( self ): + def getBitRateFactor(self): """Return bit rate factor.""" - if self.DI!=None: - return ATR.bitratefactor[ self.DI ] + if self.DI != None: + return ATR.bitratefactor[self.DI] else: return 1 - def getClockRateConversion( self ): + def getClockRateConversion(self): """Return clock rate conversion.""" - if self.FI!=None: - return ATR.clockrateconversion[ self.FI ] + if self.FI != None: + return ATR.clockrateconversion[self.FI] else: return 372 - def getProgrammingCurrent( self ): + def getProgrammingCurrent(self): """Return maximum programming current.""" - if self.II!=None: - return ATR.currenttable[ self.II ] + if self.II != None: + return ATR.currenttable[self.II] else: return 50 - def getProgrammingVoltage( self ): + def getProgrammingVoltage(self): """Return programming voltage.""" - if self.PI1!=None: - return 5*(1+self.PI1) + if self.PI1 != None: + return 5 * (1 + self.PI1) else: return 5 - def getGuardTime( self ): + def getGuardTime(self): """Return extra guard time.""" return self.N - def getSupportedProtocols( self ): + def getSupportedProtocols(self): """Returns a dictionnary of supported protocols.""" - protocols={} + protocols = {} for td in self.TD: - if td!=None: + if td != None: strprotocol = "T=%d" % (td & 0x0F) - protocols[strprotocol]=True + protocols[strprotocol] = True if not self.hasTD[0]: - protocols['T=0']=True + protocols['T=0'] = True return protocols - def isT0Supported( self ): + def isT0Supported(self): """Return True if T=0 is supported.""" - protocols=self.getSupportedProtocols() - return protocols.has_key( 'T=0' ) + protocols = self.getSupportedProtocols() + return protocols.has_key('T=0') - def isT1Supported( self ): + def isT1Supported(self): """Return True if T=1 is supported.""" - protocols=self.getSupportedProtocols() - return protocols.has_key( 'T=1' ) + protocols = self.getSupportedProtocols() + return protocols.has_key('T=1') - def isT15Supported( self ): + def isT15Supported(self): """Return True if T=15 is supported.""" - protocols=self.getSupportedProtocols() - return protocols.has_key( 'T=15' ) + protocols = self.getSupportedProtocols() + return protocols.has_key('T=15') - def dump( self ): + def dump(self): """Dump the details of an ATR.""" - for i in range( 0, len(self.TA) ): - if self.TA[i]!=None: - print "TA%d: %x" % (i+1,self.TA[i]) - if self.TB[i]!=None: - print "TB%d: %x" % (i+1,self.TB[i]) - if self.TC[i]!=None: - print "TC%d: %x" % (i+1,self.TC[i]) - if self.TD[i]!=None: - print "TD%d: %x" % (i+1,self.TD[i]) + for i in range(0, len(self.TA)): + if self.TA[i] != None: + print "TA%d: %x" % (i + 1, self.TA[i]) + if self.TB[i] != None: + print "TB%d: %x" % (i + 1, self.TB[i]) + if self.TC[i] != None: + print "TC%d: %x" % (i + 1, self.TC[i]) + if self.TD[i] != None: + print "TD%d: %x" % (i + 1, self.TD[i]) print 'supported protocols', self.getSupportedProtocols() print 'T=0 supported', self.isT0Supported() @@ -271,26 +270,24 @@ print 'nb of interface bytes:', self.getInterfaceBytesCount() print 'nb of historical bytes:', self.getHistoricalBytesCount() - - def __str__( self ): + def __str__(self): """Returns a string representation of the ATR as a strem of bytes.""" - return reduce( lambda a, b: a+"%-0.2X " % ((b+256)%256), self.bytes, '' ) + return reduce(lambda a, b: a + "%-0.2X " % ((b + 256) % 256), self.bytes, '') if __name__ == '__main__': """Small sample illustrating the use of ATR.""" - atrs = [ [ 0x3F, 0x65, 0x25, 0x00, 0x2C, 0x09, 0x69, 0x90, 0x00 ], - [ 0x3F, 0x65, 0x25, 0x08, 0x93, 0x04, 0x6C, 0x90, 0x00 ], - [ 0x3B, 0x16, 0x94, 0x7C, 0x03, 0x01, 0x00, 0x00, 0x0D ], - [ 0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03 ], - [ 0x3B, 0xE3, 0x00, 0xFF, 0x81, 0x31, 0x52, 0x45, 0xA1, 0xA2, 0xA3, 0x1B], - [ 0x3B, 0xE5, 0x00, 0x00, 0x81, 0x21, 0x45, 0x9C, 0x10, 0x01, 0x00, 0x80, 0x0D ] - ] + atrs = [[0x3F, 0x65, 0x25, 0x00, 0x2C, 0x09, 0x69, 0x90, 0x00], + [0x3F, 0x65, 0x25, 0x08, 0x93, 0x04, 0x6C, 0x90, 0x00], + [0x3B, 0x16, 0x94, 0x7C, 0x03, 0x01, 0x00, 0x00, 0x0D], + [0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03], + [0x3B, 0xE3, 0x00, 0xFF, 0x81, 0x31, 0x52, 0x45, 0xA1, 0xA2, 0xA3, 0x1B], + [0x3B, 0xE5, 0x00, 0x00, 0x81, 0x21, 0x45, 0x9C, 0x10, 0x01, 0x00, 0x80, 0x0D]] for atr in atrs: - a=ATR( atr ) - print 80*'-' + a = ATR(atr) + print 80 * '-' print a a.dump() - print reduce( lambda a, b: a+"%-0.2X " % ((b+256)%256), a.getHistoricalBytes(), '' ) + print reduce(lambda a, b: a + "%-0.2X " % ((b + 256) % 256), a.getHistoricalBytes(), '') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 18:42:22
|
Revision: 442 http://pyscard.svn.sourceforge.net/pyscard/?rev=442&view=rev Author: ludov Date: 2010-06-06 18:42:16 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/AbstractCardRequest.py Modified: trunk/pyscard/src/smartcard/AbstractCardRequest.py =================================================================== --- trunk/pyscard/src/smartcard/AbstractCardRequest.py 2010-06-06 18:39:07 UTC (rev 441) +++ trunk/pyscard/src/smartcard/AbstractCardRequest.py 2010-06-06 18:42:16 UTC (rev 442) @@ -26,6 +26,7 @@ from smartcard.PassThruCardService import PassThruCardService import smartcard.System + class AbstractCardRequest: """The base class for xxxCardRequest classes. @@ -34,19 +35,28 @@ Known subclasses: smartcard.pcsc.PCSCCardRequest""" - def __init__( self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1 ): + def __init__(self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1): """Construct new CardRequest. - newcardonly: if True, request a new card; default is False, i.e. accepts cards already inserted + newcardonly: if True, request a new card; default is + False, i.e. accepts cards already inserted - readers: the list of readers to consider for requesting a card; default is to consider all readers + readers: the list of readers to consider for + requesting a card; default is to consider + all readers - cardType: the smartcard.CardType.CardType to wait for; default is smartcard.CardType.AnyCardType, i.e. the request will succeed with any card + cardType: the smartcard.CardType.CardType to wait for; + default is smartcard.CardType.AnyCardType, + i.e. the request will succeed with any card - cardServiceClass: the specific card service class to create and bind to the card;default is to create and bind a smartcard.PassThruCardService + cardServiceClass: the specific card service class to create + and bind to the card;default is to create + and bind a smartcard.PassThruCardService - timeout: the time in seconds we are ready to wait for connecting to the requested card. - default is to wait one second; to wait forever, set timeout to None + timeout: the time in seconds we are ready to wait for + connecting to the requested card. default + is to wait one second; to wait forever, set + timeout to None """ self.newcardonly = newcardonly self.readersAsked = readers @@ -55,25 +65,25 @@ self.timeout = timeout # if no CardType requeted, use AnyCardType - if None==self.cardType: - self.cardType=AnyCardType() + if None == self.cardType: + self.cardType = AnyCardType() # if no card service requested, use pass-thru card service - if None==self.cardServiceClass: - self.cardServiceClass=PassThruCardService + if None == self.cardServiceClass: + self.cardServiceClass = PassThruCardService - def getReaders( self ): + def getReaders(self): """Returns the list or readers on which to wait for cards.""" # if readers not given, use all readers - if None==self.readersAsked: + if None == self.readersAsked: return smartcard.System.readers() else: return self.readersAsked - def waitforcard( self ): + def waitforcard(self): """Wait for card insertion and returns a card service.""" pass - def waitforcardevent( self ): + def waitforcardevent(self): """Wait for card insertion or removal.""" pass This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 18:39:14
|
Revision: 441 http://pyscard.svn.sourceforge.net/pyscard/?rev=441&view=rev Author: ludov Date: 2010-06-06 18:39:07 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/__init__.py Modified: trunk/pyscard/src/smartcard/__init__.py =================================================================== --- trunk/pyscard/src/smartcard/__init__.py 2010-06-06 16:28:54 UTC (rev 440) +++ trunk/pyscard/src/smartcard/__init__.py 2010-06-06 18:39:07 UTC (rev 441) @@ -27,12 +27,9 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ -__all__ = [ - 'listReaders', - 'Session' - ] +__all__ = ['listReaders', + 'Session'] - # for legacy only from smartcard.System import listReaders from smartcard.Session import Session This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 16:29:01
|
Revision: 440 http://pyscard.svn.sourceforge.net/pyscard/?rev=440&view=rev Author: ludov Date: 2010-06-06 16:28:54 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/wx/APDUHexValidator.py trunk/pyscard/src/smartcard/wx/APDUTracerPanel.py trunk/pyscard/src/smartcard/wx/CardAndReaderTreePanel.py trunk/pyscard/src/smartcard/wx/ReaderToolbar.py trunk/pyscard/src/smartcard/wx/SimpleSCardApp.py trunk/pyscard/src/smartcard/wx/SimpleSCardAppEventObserver.py trunk/pyscard/src/smartcard/wx/SimpleSCardAppFrame.py trunk/pyscard/src/smartcard/wx/__init__.py Modified: trunk/pyscard/src/smartcard/wx/APDUHexValidator.py =================================================================== --- trunk/pyscard/src/smartcard/wx/APDUHexValidator.py 2010-06-06 16:15:48 UTC (rev 439) +++ trunk/pyscard/src/smartcard/wx/APDUHexValidator.py 2010-06-06 16:28:54 UTC (rev 440) @@ -30,35 +30,37 @@ import wx # a regexp to match ATRs and APDUs -hexbyte="[0-9a-fA-F]{1,2}" -apduregexp = re.compile( "((%s)[ ]*)*" % hexbyte ) +hexbyte = "[0-9a-fA-F]{1,2}" +apduregexp = re.compile("((%s)[ ]*)*" % hexbyte) -class APDUHexValidator( wx.PyValidator ): + +class APDUHexValidator(wx.PyValidator): '''A wxValidator that matches APDU in hexadecimal such as: A4 A0 00 00 02 A4A0000002''' - def __init__(self ): + + def __init__(self): wx.PyValidator.__init__(self) - self.Bind( wx.EVT_CHAR, self.OnChar ) + self.Bind(wx.EVT_CHAR, self.OnChar) def Clone(self): return APDUHexValidator() - def Validate( self, win ): + def Validate(self, win): tc = self.GetWindow() val = tc.GetValue() - if not apduregexp.match( value ): + if not apduregexp.match(value): return False return True - def OnChar( self, event ): + def OnChar(self, event): key = event.GetKeyCode() - if wx.WXK_SPACE==key or chr(key) in string.hexdigits: - value = event.GetEventObject().GetValue()+chr(key) - if apduregexp.match( value ): + if wx.WXK_SPACE == key or chr(key) in string.hexdigits: + value = event.GetEventObject().GetValue() + chr(key) + if apduregexp.match(value): event.Skip() return Modified: trunk/pyscard/src/smartcard/wx/APDUTracerPanel.py =================================================================== --- trunk/pyscard/src/smartcard/wx/APDUTracerPanel.py 2010-06-06 16:15:48 UTC (rev 439) +++ trunk/pyscard/src/smartcard/wx/APDUTracerPanel.py 2010-06-06 16:28:54 UTC (rev 440) @@ -30,44 +30,44 @@ [ wxID_APDUTEXTCTRL, -] = map( lambda x: wx.NewId(), range(1) ) +] = map(lambda x: wx.NewId(), range(1)) -class APDUTracerPanel( wx.Panel, CardConnectionObserver ): - def __init__( self, parent ): - wx.Panel.__init__( self, parent, -1 ) +class APDUTracerPanel(wx.Panel, CardConnectionObserver): - boxsizer = wx.BoxSizer( wx.HORIZONTAL ) - self.apdutextctrl = wx.TextCtrl( self, wxID_APDUTEXTCTRL, "", pos=wx.DefaultPosition, style=wx.TE_MULTILINE|wx.TE_READONLY ) - boxsizer.Add( self.apdutextctrl, 1, wx.EXPAND | wx.ALL, 5 ) - self.SetSizer( boxsizer ) - self.SetAutoLayout( True ) + def __init__(self, parent): + wx.Panel.__init__(self, parent, -1) - self.Bind( wx.EVT_TEXT_MAXLEN , self.OnMaxLength, self.apdutextctrl ) + boxsizer = wx.BoxSizer(wx.HORIZONTAL) + self.apdutextctrl = wx.TextCtrl(self, wxID_APDUTEXTCTRL, "", pos=wx.DefaultPosition, style=wx.TE_MULTILINE | wx.TE_READONLY) + boxsizer.Add(self.apdutextctrl, 1, wx.EXPAND | wx.ALL, 5) + self.SetSizer(boxsizer) + self.SetAutoLayout(True) - def OnMaxLength( self, evt ): + self.Bind(wx.EVT_TEXT_MAXLEN, self.OnMaxLength, self.apdutextctrl) + + def OnMaxLength(self, evt): '''Reset text buffer when max length is reached.''' - self.apdutextctrl.SetValue( "" ) + self.apdutextctrl.SetValue("") evt.Skip() - - def update( self, cardconnection, ccevent ): + def update(self, cardconnection, ccevent): '''CardConnectionObserver callback.''' apduline = "" - if 'connect'==ccevent.type: + if 'connect' == ccevent.type: apduline += 'connecting to ' + cardconnection.getReader() - elif 'disconnect'==ccevent.type: + elif 'disconnect' == ccevent.type: apduline += 'disconnecting from ' + cardconnection.getReader() - elif 'command'==ccevent.type: - apduline += '> ' + toHexString( ccevent.args[0] ) + elif 'command' == ccevent.type: + apduline += '> ' + toHexString(ccevent.args[0]) - elif 'response'==ccevent.type: - if []==ccevent.args[0]: + elif 'response' == ccevent.type: + if [] == ccevent.args[0]: apduline += "< %-2X %-2X" % tuple(ccevent.args[-2:]) else: - apduline += "< " + toHexString( ccevent.args[0]) + "%-2X %-2X" % tuple(ccevent.args[-2:] ) + apduline += "< " + toHexString(ccevent.args[0]) + "%-2X %-2X" % tuple(ccevent.args[-2:]) - self.apdutextctrl.AppendText( apduline + "\n" ) + self.apdutextctrl.AppendText(apduline + "\n") Modified: trunk/pyscard/src/smartcard/wx/CardAndReaderTreePanel.py =================================================================== --- trunk/pyscard/src/smartcard/wx/CardAndReaderTreePanel.py 2010-06-06 16:15:48 UTC (rev 439) +++ trunk/pyscard/src/smartcard/wx/CardAndReaderTreePanel.py 2010-06-06 16:28:54 UTC (rev 440) @@ -35,128 +35,133 @@ # wxPython GUI modules (http://www.wxpython.org) import wx -class BaseCardTreeCtrl( wx.TreeCtrl ): + +class BaseCardTreeCtrl(wx.TreeCtrl): """Base class for the smart card and reader tree controls.""" - def __init__( self, + + def __init__(self, parent, ID=wx.NewId(), pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, - clientpanel=None ): + clientpanel=None): """Constructor. Initializes a smartcard or reader tree control.""" - wx.TreeCtrl.__init__( self, parent, ID, pos, size , wx.TR_SINGLE | wx.TR_NO_BUTTONS ) + wx.TreeCtrl.__init__(self, parent, ID, pos, size, wx.TR_SINGLE | wx.TR_NO_BUTTONS) self.clientpanel = clientpanel self.parent = parent - isz = (16,16) - il = wx.ImageList( isz[0], isz[1] ) - self.capindex = il.Add( wx.ArtProvider_GetBitmap( wx.ART_HELP_BOOK, wx.ART_OTHER, isz )) - self.fldrindex = il.Add( wx.ArtProvider_GetBitmap( wx.ART_FOLDER, wx.ART_OTHER, isz ) ) - self.fldropenindex = il.Add( wx.ArtProvider_GetBitmap( wx.ART_FILE_OPEN, wx.ART_OTHER, isz ) ) - if None!=ICO_SMARTCARD: - self.cardimageindex = il.Add( wx.Bitmap( ICO_SMARTCARD, wx.BITMAP_TYPE_ICO ) ) - if None!=ICO_READER: - self.readerimageindex = il.Add( wx.Bitmap( ICO_READER, wx.BITMAP_TYPE_ICO ) ) + isz = (16, 16) + il = wx.ImageList(isz[0], isz[1]) + self.capindex = il.Add(wx.ArtProvider_GetBitmap(wx.ART_HELP_BOOK, wx.ART_OTHER, isz)) + self.fldrindex = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, isz)) + self.fldropenindex = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, isz)) + if None != ICO_SMARTCARD: + self.cardimageindex = il.Add(wx.Bitmap(ICO_SMARTCARD, wx.BITMAP_TYPE_ICO)) + if None != ICO_READER: + self.readerimageindex = il.Add(wx.Bitmap(ICO_READER, wx.BITMAP_TYPE_ICO)) self.il = il self.SetImageList(self.il) - def Repaint( self ): + def Repaint(self): self.Refresh() - wx.PostEvent( self, wx.PaintEvent() ) + wx.PostEvent(self, wx.PaintEvent()) -class CardTreeCtrl( BaseCardTreeCtrl ): +class CardTreeCtrl(BaseCardTreeCtrl): """The CardTreeCtrl monitors inserted cards and notifies the application client dialog of any card activation.""" - def __init__( self, + + def __init__(self, parent, ID=wx.NewId(), pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, - clientpanel=None ): + clientpanel=None): """Constructor. Create a smartcard tree control.""" - BaseCardTreeCtrl.__init__( self, parent, ID, pos, size , + BaseCardTreeCtrl.__init__(self, parent, ID, pos, size, wx.TR_SINGLE | wx.TR_NO_BUTTONS, - clientpanel ) + clientpanel) self.root = self.AddRoot("Smartcards") - self.SetPyData( self.root, None ) - self.SetItemImage( self.root, self.fldrindex, wx.TreeItemIcon_Normal ) - self.SetItemImage( self.root, self.fldropenindex, wx.TreeItemIcon_Expanded ) + self.SetPyData(self.root, None) + self.SetItemImage(self.root, self.fldrindex, wx.TreeItemIcon_Normal) + self.SetItemImage(self.root, self.fldropenindex, wx.TreeItemIcon_Expanded) self.Expand(self.root) - def OnAddCards( self, addedcards ): + def OnAddCards(self, addedcards): """Called when a card is inserted. Adds a smart card to the smartcards tree.""" - parentnode=self.root + parentnode = self.root for cardtoadd in addedcards: - childCard = self.AppendItem( parentnode, toHexString(cardtoadd.atr) ) - self.SetItemText( childCard, toHexString(cardtoadd.atr) ) - self.SetPyData( childCard, cardtoadd ) - self.SetItemImage( childCard, self.cardimageindex, wx.TreeItemIcon_Normal ) - self.SetItemImage( childCard, self.cardimageindex, wx.TreeItemIcon_Expanded ) + childCard = self.AppendItem(parentnode, toHexString(cardtoadd.atr)) + self.SetItemText(childCard, toHexString(cardtoadd.atr)) + self.SetPyData(childCard, cardtoadd) + self.SetItemImage(childCard, self.cardimageindex, wx.TreeItemIcon_Normal) + self.SetItemImage(childCard, self.cardimageindex, wx.TreeItemIcon_Expanded) self.Expand(childCard) self.Expand(self.root) - self.EnsureVisible( self.root ) + self.EnsureVisible(self.root) self.Repaint() - def OnRemoveCards( self, removedcards ): + def OnRemoveCards(self, removedcards): """Called when a card is removed. Removes a card from the tree.""" - parentnode=self.root + parentnode = self.root for cardtoremove in removedcards: - ( childCard, cookie ) = self.GetFirstChild( parentnode ) + (childCard, cookie) = self.GetFirstChild(parentnode) while childCard.IsOk(): - if self.GetItemText( childCard )==toHexString( cardtoremove.atr ): - self.Delete( childCard ) - ( childCard, cookie ) = self.GetNextChild( parentnode, cookie ) + if self.GetItemText(childCard) == toHexString(cardtoremove.atr): + self.Delete(childCard) + (childCard, cookie) = self.GetNextChild(parentnode, cookie) self.Expand(self.root) - self.EnsureVisible( self.root ) + self.EnsureVisible(self.root) self.Repaint() -class ReaderTreeCtrl( BaseCardTreeCtrl ): + +class ReaderTreeCtrl(BaseCardTreeCtrl): """The ReaderTreeCtrl monitors inserted cards and readers and notifies the application client dialog of any card activation.""" - def __init__( self, + + def __init__(self, parent, ID=wx.NewId(), pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, - clientpanel=None ): + clientpanel=None): """Constructor. Create a reader tree control.""" - BaseCardTreeCtrl.__init__( self, parent, ID, pos, size , - wx.TR_SINGLE | wx.TR_NO_BUTTONS, clientpanel ) + BaseCardTreeCtrl.__init__(self, parent, ID, pos, size, + wx.TR_SINGLE | wx.TR_NO_BUTTONS, clientpanel) self.mutex = RLock() self.root = self.AddRoot("Smartcard Readers") - self.SetPyData( self.root, None ) - self.SetItemImage( self.root, self.fldrindex, wx.TreeItemIcon_Normal ) - self.SetItemImage( self.root, self.fldropenindex, wx.TreeItemIcon_Expanded ) + self.SetPyData(self.root, None) + self.SetItemImage(self.root, self.fldrindex, wx.TreeItemIcon_Normal) + self.SetItemImage(self.root, self.fldropenindex, wx.TreeItemIcon_Expanded) self.Expand(self.root) - def AddATR( self, readernode, atr ): + def AddATR(self, readernode, atr): """Add an ATR to a reader node.""" - capchild = self.AppendItem( readernode, atr ) - self.SetPyData( capchild, None ) - self.SetItemImage( capchild, self.cardimageindex, wx.TreeItemIcon_Normal ) - self.SetItemImage( capchild, self.cardimageindex, wx.TreeItemIcon_Expanded ) + capchild = self.AppendItem(readernode, atr) + self.SetPyData(capchild, None) + self.SetItemImage(capchild, self.cardimageindex, wx.TreeItemIcon_Normal) + self.SetItemImage(capchild, self.cardimageindex, wx.TreeItemIcon_Expanded) self.Expand(capchild) return capchild - def GetATR( self, reader ): + def GetATR(self, reader): """Return the ATR of the card inserted into the reader.""" - atr="no card inserted" + atr = "no card inserted" try: - if not type( reader ) is str: - connection=reader.createConnection() + if not type(reader) is str: + connection = reader.createConnection() connection.connect() - atr=toHexString( connection.getATR() ) + atr = toHexString(connection.getATR()) connection.disconnect() except NoCardException: pass @@ -164,199 +169,197 @@ pass return atr - def OnAddCards( self, addedcards ): + def OnAddCards(self, addedcards): """Called when a card is inserted. Adds the smart card child to the reader node.""" self.mutex.acquire() try: - parentnode=self.root + parentnode = self.root for cardtoadd in addedcards: - ( childReader, cookie ) = self.GetFirstChild( parentnode ) - found=False + (childReader, cookie) = self.GetFirstChild(parentnode) + found = False while childReader.IsOk() and not found: - if self.GetItemText( childReader )==str( cardtoadd.reader ): - ( childCard, cookie2 ) = self.GetFirstChild( childReader ) - self.SetItemText( childCard, toHexString( cardtoadd.atr) ) - self.SetPyData( childCard, cardtoadd ) - found=True + if self.GetItemText(childReader) == str(cardtoadd.reader): + (childCard, cookie2) = self.GetFirstChild(childReader) + self.SetItemText(childCard, toHexString(cardtoadd.atr)) + self.SetPyData(childCard, cardtoadd) + found = True else: - ( childReader, cookie ) = self.GetNextChild( parentnode, cookie ) + (childReader, cookie) = self.GetNextChild(parentnode, cookie) # reader was not found, add reader node # this happens when card monitoring thread signals # added cards before reader monitoring thread signals # added readers if not found: - childReader = self.AppendItem( parentnode, str(cardtoadd.reader) ) - self.SetPyData( childReader, cardtoadd.reader ) - self.SetItemImage( childReader, self.readerimageindex, wx.TreeItemIcon_Normal ) - self.SetItemImage( childReader, self.readerimageindex, wx.TreeItemIcon_Expanded ) - childCard = self.AddATR( childReader, toHexString( cardtoadd.atr ) ) - self.SetPyData( childCard, cardtoadd ) - self.Expand( childReader ) + childReader = self.AppendItem(parentnode, str(cardtoadd.reader)) + self.SetPyData(childReader, cardtoadd.reader) + self.SetItemImage(childReader, self.readerimageindex, wx.TreeItemIcon_Normal) + self.SetItemImage(childReader, self.readerimageindex, wx.TreeItemIcon_Expanded) + childCard = self.AddATR(childReader, toHexString(cardtoadd.atr)) + self.SetPyData(childCard, cardtoadd) + self.Expand(childReader) self.Expand(self.root) finally: self.mutex.release() - self.EnsureVisible( self.root ) + self.EnsureVisible(self.root) self.Repaint() - def OnAddReaders( self, addedreaders ): + def OnAddReaders(self, addedreaders): """Called when a reader is inserted. Adds the smart card reader to the smartcard readers tree.""" self.mutex.acquire() try: - parentnode=self.root + parentnode = self.root for readertoadd in addedreaders: # is the reader already here? found = False - ( childReader, cookie ) = self.GetFirstChild( parentnode ) + (childReader, cookie) = self.GetFirstChild(parentnode) while childReader.IsOk() and not found: - if self.GetItemText( childReader )==str( readertoadd ): - found=True + if self.GetItemText(childReader) == str(readertoadd): + found = True else: - ( childReader, cookie ) = self.GetNextChild( parentnode, cookie ) + (childReader, cookie) = self.GetNextChild(parentnode, cookie) if not found: - childReader = self.AppendItem( parentnode, str(readertoadd) ) - self.SetPyData( childReader, readertoadd ) - self.SetItemImage( childReader, self.readerimageindex, wx.TreeItemIcon_Normal ) - self.SetItemImage( childReader, self.readerimageindex, wx.TreeItemIcon_Expanded ) - self.AddATR( childReader, self.GetATR( readertoadd) ) + childReader = self.AppendItem(parentnode, str(readertoadd)) + self.SetPyData(childReader, readertoadd) + self.SetItemImage(childReader, self.readerimageindex, wx.TreeItemIcon_Normal) + self.SetItemImage(childReader, self.readerimageindex, wx.TreeItemIcon_Expanded) + self.AddATR(childReader, self.GetATR(readertoadd)) self.Expand(childReader) self.Expand(self.root) finally: self.mutex.release() - self.EnsureVisible( self.root ) + self.EnsureVisible(self.root) self.Repaint() - - def OnRemoveCards( self, removedcards ): + def OnRemoveCards(self, removedcards): """Called when a card is removed. Removes the card from the tree.""" self.mutex.acquire() try: - parentnode=self.root + parentnode = self.root for cardtoremove in removedcards: - ( childReader, cookie ) = self.GetFirstChild( parentnode ) - found=False + (childReader, cookie) = self.GetFirstChild(parentnode) + found = False while childReader.IsOk() and not found: - if self.GetItemText( childReader )==str( cardtoremove.reader ): - ( childCard, cookie2 ) = self.GetFirstChild( childReader ) - self.SetItemText( childCard, 'no card inserted' ) - found=True + if self.GetItemText(childReader) == str(cardtoremove.reader): + (childCard, cookie2) = self.GetFirstChild(childReader) + self.SetItemText(childCard, 'no card inserted') + found = True else: - ( childReader, cookie ) = self.GetNextChild( parentnode, cookie ) + (childReader, cookie) = self.GetNextChild(parentnode, cookie) self.Expand(self.root) finally: self.mutex.release() - self.EnsureVisible( self.root ) + self.EnsureVisible(self.root) self.Repaint() - def OnRemoveReaders( self, removedreaders ): + def OnRemoveReaders(self, removedreaders): """Called when a reader is removed. Removes the reader from the smartcard readers tree.""" self.mutex.acquire() try: - parentnode=self.root + parentnode = self.root for readertoremove in removedreaders: - ( childReader, cookie ) = self.GetFirstChild( parentnode ) + (childReader, cookie) = self.GetFirstChild(parentnode) while childReader.IsOk(): - if self.GetItemText( childReader )==str( readertoremove ): - self.Delete( childReader ) + if self.GetItemText(childReader) == str(readertoremove): + self.Delete(childReader) else: - ( childReader, cookie ) = self.GetNextChild( parentnode, cookie ) + (childReader, cookie) = self.GetNextChild(parentnode, cookie) self.Expand(self.root) finally: self.mutex.release() - self.EnsureVisible( self.root ) + self.EnsureVisible(self.root) self.Repaint() -class CardAndReaderTreePanel( wx.Panel ): + +class CardAndReaderTreePanel(wx.Panel): """Panel containing the smart card and reader tree controls.""" - class _CardObserver( CardObserver ): + class _CardObserver(CardObserver): """Inner CardObserver. Gets notified of card insertion removal by the CardMonitor.""" - def __init__( self, cardtreectrl ): + def __init__(self, cardtreectrl): self.cardtreectrl = cardtreectrl - def update( self, observable, (addedcards, removedcards) ): + def update(self, observable, (addedcards, removedcards)): """CardObserver callback that is notified when cards are added or removed.""" - self.cardtreectrl.OnRemoveCards( removedcards ) - self.cardtreectrl.OnAddCards( addedcards ) + self.cardtreectrl.OnRemoveCards(removedcards) + self.cardtreectrl.OnAddCards(addedcards) - class _ReaderObserver( ReaderObserver ): + class _ReaderObserver(ReaderObserver): """Inner ReaderObserver. Gets notified of reader insertion/removal by the ReaderMonitor.""" - def __init__( self, readertreectrl ): + def __init__(self, readertreectrl): self.readertreectrl = readertreectrl - def update( self, observable, (addedreaders, removedreaders) ): + def update(self, observable, (addedreaders, removedreaders)): """ReaderObserver callback that is notified when readers are added or removed.""" - self.readertreectrl.OnRemoveReaders( removedreaders ) - self.readertreectrl.OnAddReaders( addedreaders ) + self.readertreectrl.OnRemoveReaders(removedreaders) + self.readertreectrl.OnAddReaders(addedreaders) - - def __init__( self, parent, appstyle, clientpanel ): + def __init__(self, parent, appstyle, clientpanel): """Constructor. Create a smartcard and reader tree control on the left-hand side of the application main frame. parent: the tree panel parent - appstyle: a combination of the following styles (bitwise or | ) + appstyle: a combination of the following styles (bitwise or |) TR_SMARTCARD: display a smartcard tree panel TR_READER: display a reader tree panel default is TR_DEFAULT = TR_SMARTCARD clientpanel: the client panel to notify of smartcard and reader events """ - wx.Panel.__init__( self, parent, -1, style=wx.WANTS_CHARS ) + wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS) - sizer = wx.BoxSizer( wx.VERTICAL ) + sizer = wx.BoxSizer(wx.VERTICAL) # create the smartcard tree if appstyle & smartcard.wx.SimpleSCardApp.TR_SMARTCARD: - self.cardtreectrl = CardTreeCtrl( self, clientpanel=clientpanel ) + self.cardtreectrl = CardTreeCtrl(self, clientpanel=clientpanel) # create the smartcard insertion observer - self.cardtreecardobserver = self._CardObserver( self.cardtreectrl ) + self.cardtreecardobserver = self._CardObserver(self.cardtreectrl) # register as a CardObserver; we will ge notified of added/removed cards self.cardmonitor = CardMonitor() - self.cardmonitor.addObserver( self.cardtreecardobserver ) + self.cardmonitor.addObserver(self.cardtreecardobserver) - sizer.Add( self.cardtreectrl, flag=wx.EXPAND | wx.ALL, proportion=1 ) + sizer.Add(self.cardtreectrl, flag=wx.EXPAND | wx.ALL, proportion=1) # create the reader tree if appstyle & smartcard.wx.SimpleSCardApp.TR_READER: - self.readertreectrl = ReaderTreeCtrl( self, clientpanel=clientpanel ) + self.readertreectrl = ReaderTreeCtrl(self, clientpanel=clientpanel) # create the reader insertion observer - self.readertreereaderobserver = self._ReaderObserver( self.readertreectrl ) + self.readertreereaderobserver = self._ReaderObserver(self.readertreectrl) # register as a ReaderObserver; we will ge notified of added/removed readers self.readermonitor = ReaderMonitor() - self.readermonitor.addObserver( self.readertreereaderobserver ) + self.readermonitor.addObserver(self.readertreereaderobserver) # create the smartcard insertion observer - self.readertreecardobserver = self._CardObserver( self.readertreectrl ) + self.readertreecardobserver = self._CardObserver(self.readertreectrl) # register as a CardObserver; we will ge notified of added/removed cards self.cardmonitor = CardMonitor() - self.cardmonitor.addObserver( self.readertreecardobserver ) + self.cardmonitor.addObserver(self.readertreecardobserver) - sizer.Add( self.readertreectrl, flag=wx.EXPAND | wx.ALL, proportion=1 ) + sizer.Add(self.readertreectrl, flag=wx.EXPAND | wx.ALL, proportion=1) self.SetSizer(sizer) self.SetAutoLayout(True) - def OnDestroy(self, event): """Called on panel destruction.""" # deregister observers - if hasattr( self, cardmonitor ): - self.cardmonitor.deleteObserver( self.cardtreecardobserver ) - if hasattr( self, readermonitor ): - self.readermonitor.deleteObserver( self.readertreereaderobserver ) - self.cardmonitor.deleteObserver( self.readertreecardobserver ) + if hasattr(self, cardmonitor): + self.cardmonitor.deleteObserver(self.cardtreecardobserver) + if hasattr(self, readermonitor): + self.readermonitor.deleteObserver(self.readertreereaderobserver) + self.cardmonitor.deleteObserver(self.readertreecardobserver) event.Skip() Modified: trunk/pyscard/src/smartcard/wx/ReaderToolbar.py =================================================================== --- trunk/pyscard/src/smartcard/wx/ReaderToolbar.py 2010-06-06 16:15:48 UTC (rev 439) +++ trunk/pyscard/src/smartcard/wx/ReaderToolbar.py 2010-06-06 16:28:54 UTC (rev 440) @@ -27,60 +27,63 @@ from smartcard.ReaderMonitoring import ReaderMonitor, ReaderObserver from smartcard.wx import ICO_SMARTCARD, ICO_READER -class ReaderComboBox( wx.ComboBox, ReaderObserver ): - def __init__( self, parent ): + +class ReaderComboBox(wx.ComboBox, ReaderObserver): + + def __init__(self, parent): """Constructor. Registers as ReaderObserver to get notifications of reader insertion/removal.""" - wx.ComboBox.__init__( self, parent, wx.NewId(), - size=(170,-1), style=wx.CB_DROPDOWN | wx.CB_SORT , - choices=[] ) + wx.ComboBox.__init__(self, parent, wx.NewId(), + size=(170, -1), style=wx.CB_DROPDOWN | wx.CB_SORT, + choices=[]) # register as a ReaderObserver; we will ge notified of added/removed readers self.readermonitor = ReaderMonitor() - self.readermonitor.addObserver( self ) + self.readermonitor.addObserver(self) - def update( self, observable, (addedreaders, removedreaders) ): + def update(self, observable, (addedreaders, removedreaders)): """Toolbar ReaderObserver callback that is notified when readers are added or removed.""" for reader in addedreaders: - item = self.Append( str(reader) ) - self.SetClientData( item, reader ) + item = self.Append(str(reader)) + self.SetClientData(item, reader) for reader in removedreaders: - item = self.FindString( str(reader) ) + item = self.FindString(str(reader)) if wx.NOT_FOUND != item: - self.Delete( item ) + self.Delete(item) selection = self.GetSelection() #if wx.NOT_FOUND == selection: - # self.SetSelection( 0 ) + # self.SetSelection(0) -class ReaderToolbar( wx.ToolBar ): +class ReaderToolbar(wx.ToolBar): """ReaderToolbar. Contains controls to select a reader from a listbox and connect to the cards.""" - def __init__( self, parent ): + + def __init__(self, parent): """Constructor, creating the reader toolbar.""" - wx.ToolBar.__init__( self, + wx.ToolBar.__init__(self, parent, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.SIMPLE_BORDER | wx.TB_HORIZONTAL | wx.TB_FLAT | wx.TB_TEXT, - name='Reader Toolbar' ) + name='Reader Toolbar') # create bitmaps for toolbar - tsize = (16,16) - if None!=ICO_READER: - bmpReader = wx.Bitmap( ICO_READER, wx.BITMAP_TYPE_ICO ) + tsize = (16, 16) + if None != ICO_READER: + bmpReader = wx.Bitmap(ICO_READER, wx.BITMAP_TYPE_ICO) else: - bmpReader = wx.ArtProvider_GetBitmap( wx.ART_HELP_BOOK, wx.ART_OTHER, isz ) - if None!=ICO_SMARTCARD: - bmpCard = wx.Bitmap( ICO_SMARTCARD, wx.BITMAP_TYPE_ICO ) + bmpReader = wx.ArtProvider_GetBitmap(wx.ART_HELP_BOOK, wx.ART_OTHER, isz) + if None != ICO_SMARTCARD: + bmpCard = wx.Bitmap(ICO_SMARTCARD, wx.BITMAP_TYPE_ICO) else: - bmpCard = wx.ArtProvider_GetBitmap( wx.ART_HELP_BOOK, wx.ART_OTHER, isz ) - self.readercombobox = ReaderComboBox( self ) + bmpCard = wx.ArtProvider_GetBitmap(wx.ART_HELP_BOOK, wx.ART_OTHER, isz) + self.readercombobox = ReaderComboBox(self) # create and add controls - self.AddSimpleTool( 10, bmpReader, "Select smart card reader", "Select smart card reader") - self.AddControl( self.readercombobox ) + self.AddSimpleTool(10, bmpReader, "Select smart card reader", "Select smart card reader") + self.AddControl(self.readercombobox) self.AddSeparator() self.AddSimpleTool(20, bmpCard, "Connect to smartcard", "Connect to smart card") self.AddSeparator() Modified: trunk/pyscard/src/smartcard/wx/SimpleSCardApp.py =================================================================== --- trunk/pyscard/src/smartcard/wx/SimpleSCardApp.py 2010-06-06 16:15:48 UTC (rev 439) +++ trunk/pyscard/src/smartcard/wx/SimpleSCardApp.py 2010-06-06 16:28:54 UTC (rev 440) @@ -33,22 +33,24 @@ PANEL_APDUTRACER = 0x010 TR_DEFAULT = TR_SMARTCARD -class SimpleSCardApp( wx.App ): + +class SimpleSCardApp(wx.App): """The SimpleSCardApp class represents the smart card application. SimpleSCardApp is a subclass of wx.App. """ - def __init__( self, + + def __init__(self, appname='', apppanel=None, appstyle=TR_DEFAULT, appicon=None, - pos=(-1,-1), - size=(-1,-1) ): + pos=(-1, -1), + size=(-1, -1)): """Constructor for simple smart card application. appname: the application name apppanel: the application panel to display in the application frame appicon: the application icon file; the default is no icon - appstyle: a combination of the following styles (bitwise or | ) + appstyle: a combination of the following styles (bitwise or |) TR_SMARTCARD: display a smartcard tree panel TR_READER: display a reader tree panel TB_SMARTCARD: display a smartcard toolbar @@ -63,7 +65,7 @@ appname = 'A simple smartcard application', apppanel = testpanel.MyPanel, appstyle = TR_READER | TR_SMARTCARD, - appicon = 'resources\mysmartcard.ico' ) + appicon = 'resources\mysmartcard.ico') """ self.appname = appname self.apppanel = apppanel @@ -71,7 +73,7 @@ self.appicon = appicon self.pos = pos self.size = size - wx.App.__init__( self, False ) + wx.App.__init__(self, False) def OnInit(self): """Create and display application frame.""" @@ -81,8 +83,8 @@ self.appstyle, self.appicon, self.pos, - self.size ) - self.frame.Show( True ) - self.SetTopWindow( self.frame ) + self.size) + self.frame.Show(True) + self.SetTopWindow(self.frame) return True Modified: trunk/pyscard/src/smartcard/wx/SimpleSCardAppEventObserver.py =================================================================== --- trunk/pyscard/src/smartcard/wx/SimpleSCardAppEventObserver.py 2010-06-06 16:15:48 UTC (rev 439) +++ trunk/pyscard/src/smartcard/wx/SimpleSCardAppEventObserver.py 2010-06-06 16:28:54 UTC (rev 440) @@ -22,33 +22,35 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ + class SimpleSCardAppEventObserver: """This interface defines the event handlers called by the SimpleSCardApp.""" - def __init__( self ): + + def __init__(self): self.selectedcard = None self.selectedreader = None # callbacks from SimpleCardAppFrame controls - def OnActivateCard( self, card ): + def OnActivateCard(self, card): """Called when a card is activated in the reader tree control or toolbar.""" self.selectedcard = card - def OnActivateReader( self, reader ): + def OnActivateReader(self, reader): """Called when a reader is activated in the reader tree control or toolbar.""" self.selectedreader = reader - def OnDeactivateCard( self, card ): + def OnDeactivateCard(self, card): """Called when a card is deactivated in the reader tree control or toolbar.""" pass - def OnDeselectCard( self, card ): + def OnDeselectCard(self, card): """Called when a card is selected in the reader tree control or toolbar.""" self.selectedcard = None - def OnSelectCard( self, card ): + def OnSelectCard(self, card): """Called when a card is selected in the reader tree control or toolbar.""" self.selectedcard = card - def OnSelectReader( self, reader ): + def OnSelectReader(self, reader): """Called when a reader is selected in the reader tree control or toolbar.""" self.selectedreader = reader Modified: trunk/pyscard/src/smartcard/wx/SimpleSCardAppFrame.py =================================================================== --- trunk/pyscard/src/smartcard/wx/SimpleSCardAppFrame.py 2010-06-06 16:15:48 UTC (rev 439) +++ trunk/pyscard/src/smartcard/wx/SimpleSCardAppFrame.py 2010-06-06 16:28:54 UTC (rev 440) @@ -36,202 +36,201 @@ [ wxID_SIMPLESCARDAPP_FRAME, -] = map( lambda x: wx.NewId(), range(1) ) +] = map(lambda x: wx.NewId(), range(1)) -class BlankPanel( wx.Panel, SimpleSCardAppEventObserver ): +class BlankPanel(wx.Panel, SimpleSCardAppEventObserver): '''A blank panel in case no panel is provided to SimpleSCardApp.''' - def __init__( self, parent ): - wx.Panel.__init__( self, parent, -1 ) - sizer = wx.GridSizer( 1, 1 ) + + def __init__(self, parent): + wx.Panel.__init__(self, parent, -1) + sizer = wx.GridSizer(1, 1) self.SetSizer(sizer) self.SetAutoLayout(True) -class TreeAndUserPanelPanel( wx.Panel ): +class TreeAndUserPanelPanel(wx.Panel): '''The panel that contains the Card/Reader TreeCtrl and the user provided Panel.''' - def __init__( self, parent, apppanelclass, appstyle ): + + def __init__(self, parent, apppanelclass, appstyle): """ Constructor. Creates the panel with two panels: the left-hand panel is holding the smartcard and/or reader tree the right-hand panel is holding the application dialog apppanelclass: the class of the panel to instantiate in the SimpleSCardAppFrame - appstyle: a combination of the following styles (bitwise or | ) + appstyle: a combination of the following styles (bitwise or |) TR_SMARTCARD: display a smartcard tree panel TR_READER: display a reader tree panel TB_SMARTCARD: display a smartcard toolbar TB_SMARTCARD: display a reader toolbar default is TR_DEFAULT = TR_SMARTCARD """ - wx.Panel.__init__( self, parent, -1 ) + wx.Panel.__init__(self, parent, -1) self.parent = parent self.selectedcard = None - boxsizer = wx.BoxSizer( wx.HORIZONTAL ) + boxsizer = wx.BoxSizer(wx.HORIZONTAL) # create user dialog - if None!=apppanelclass: - self.dialogpanel=apppanelclass( self ) + if None != apppanelclass: + self.dialogpanel = apppanelclass(self) else: - self.dialogpanel=BlankPanel( self ) + self.dialogpanel = BlankPanel(self) # create card/reader tree control if appstyle & smartcard.wx.SimpleSCardApp.TR_SMARTCARD or \ appstyle & smartcard.wx.SimpleSCardApp.TR_READER: - self.readertreepanel = CardAndReaderTreePanel.CardAndReaderTreePanel( - self, appstyle, self.dialogpanel ) - boxsizer.Add( self.readertreepanel, 1, wx.EXPAND|wx.ALL, 5 ) + self.readertreepanel = CardAndReaderTreePanel.CardAndReaderTreePanel(self, appstyle, self.dialogpanel) + boxsizer.Add(self.readertreepanel, 1, wx.EXPAND | wx.ALL, 5) + boxsizer.Add(self.dialogpanel, 2, wx.EXPAND | wx.ALL) - boxsizer.Add( self.dialogpanel, 2, wx.EXPAND | wx.ALL ) - if appstyle & smartcard.wx.SimpleSCardApp.TR_READER: - self.Bind( wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivateReader, self.readertreepanel.readertreectrl ) - self.Bind( wx.EVT_TREE_SEL_CHANGED, self.OnSelectReader, self.readertreepanel.readertreectrl ) - self.Bind( wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnReaderRightClick, self.readertreepanel.readertreectrl ) - self.Bind( wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.readertreepanel.readertreectrl ) + self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivateReader, self.readertreepanel.readertreectrl) + self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectReader, self.readertreepanel.readertreectrl) + self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnReaderRightClick, self.readertreepanel.readertreectrl) + self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.readertreepanel.readertreectrl) if appstyle & smartcard.wx.SimpleSCardApp.TR_SMARTCARD: - self.Bind( wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivateCard, self.readertreepanel.cardtreectrl ) - self.Bind( wx.EVT_TREE_SEL_CHANGED, self.OnSelectCard, self.readertreepanel.cardtreectrl ) - self.Bind( wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnCardRightClick, self.readertreepanel.cardtreectrl ) + self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivateCard, self.readertreepanel.cardtreectrl) + self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelectCard, self.readertreepanel.cardtreectrl) + self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnCardRightClick, self.readertreepanel.cardtreectrl) - self.SetSizer( boxsizer ) - self.SetAutoLayout( True ) + self.SetSizer(boxsizer) + self.SetAutoLayout(True) - def ActivateCard( self, card ): + def ActivateCard(self, card): """Activate a card.""" - if not hasattr( card, 'connection' ): + if not hasattr(card, 'connection'): card.connection = card.createConnection() - if None!=self.parent.apdutracerpanel: - card.connection.addObserver( self.parent.apdutracerpanel ) + if None != self.parent.apdutracerpanel: + card.connection.addObserver(self.parent.apdutracerpanel) card.connection.connect() - self.dialogpanel.OnActivateCard( card ) + self.dialogpanel.OnActivateCard(card) - def DeactivateCard( self, card ): + def DeactivateCard(self, card): """Deactivate a card.""" - if hasattr( card, 'connection' ): + if hasattr(card, 'connection'): card.connection.disconnect() - if None!=self.parent.apdutracerpanel: - card.connection.deleteObserver( self.parent.apdutracerpanel ) - delattr( card, 'connection' ) - self.dialogpanel.OnDeactivateCard( card ) + if None != self.parent.apdutracerpanel: + card.connection.deleteObserver(self.parent.apdutracerpanel) + delattr(card, 'connection') + self.dialogpanel.OnDeactivateCard(card) - - def OnActivateCard( self, event ): + def OnActivateCard(self, event): """Called when the user activates a card in the tree.""" item = event.GetItem() if item: - itemdata = self.readertreepanel.cardtreectrl.GetItemPyData( item ) - if isinstance( itemdata, smartcard.Card.Card ): - self.ActivateCard( itemdata ) + itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item) + if isinstance(itemdata, smartcard.Card.Card): + self.ActivateCard(itemdata) else: - self.dialogpanel.OnDeselectCard( itemdata ) + self.dialogpanel.OnDeselectCard(itemdata) - def OnActivateReader( self, event ): + def OnActivateReader(self, event): """Called when the user activates a reader in the tree.""" item = event.GetItem() if item: - itemdata = self.readertreepanel.readertreectrl.GetItemPyData( item ) - if isinstance( itemdata, smartcard.Card.Card ): - self.ActivateCard( itemdata ) - elif isinstance( itemdata, smartcard.reader.Reader.Reader ): - self.dialogpanel.OnActivateReader( itemdata ) + itemdata = self.readertreepanel.readertreectrl.GetItemPyData(item) + if isinstance(itemdata, smartcard.Card.Card): + self.ActivateCard(itemdata) + elif isinstance(itemdata, smartcard.reader.Reader.Reader): + self.dialogpanel.OnActivateReader(itemdata) event.Skip() - def OnItemCollapsed( self, event ): + def OnItemCollapsed(self, event): item = event.GetItem() - self.readertreepanel.readertreectrl.Expand( item ) + self.readertreepanel.readertreectrl.Expand(item) - def OnCardRightClick( self, event ): + def OnCardRightClick(self, event): """Called when the user right-clicks a node in the card tree control.""" item = event.GetItem() if item: - itemdata = self.readertreepanel.cardtreectrl.GetItemPyData( item ) - if isinstance( itemdata, smartcard.Card.Card ): + itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item) + if isinstance(itemdata, smartcard.Card.Card): self.selectedcard = itemdata if not hasattr(self, "connectID"): self.connectID = wx.NewId() self.disconnectID = wx.NewId() - self.Bind( wx.EVT_MENU, self.OnConnect, id=self.connectID ) - self.Bind( wx.EVT_MENU, self.OnDisconnect, id=self.disconnectID ) + self.Bind(wx.EVT_MENU, self.OnConnect, id=self.connectID) + self.Bind(wx.EVT_MENU, self.OnDisconnect, id=self.disconnectID) menu = wx.Menu() - if not hasattr( self.selectedcard, 'connection' ): - menu.Append( self.connectID, "Connect" ) + if not hasattr(self.selectedcard, 'connection'): + menu.Append(self.connectID, "Connect") else: - menu.Append( self.disconnectID, "Disconnect" ) - self.PopupMenu( menu ) + menu.Append(self.disconnectID, "Disconnect") + self.PopupMenu(menu) menu.Destroy() - - def OnReaderRightClick( self, event ): + def OnReaderRightClick(self, event): """Called when the user right-clicks a node in the reader tree control.""" item = event.GetItem() if item: - itemdata = self.readertreepanel.readertreectrl.GetItemPyData( item ) - if isinstance( itemdata, smartcard.Card.Card ): + itemdata = self.readertreepanel.readertreectrl.GetItemPyData(item) + if isinstance(itemdata, smartcard.Card.Card): self.selectedcard = itemdata if not hasattr(self, "connectID"): self.connectID = wx.NewId() self.disconnectID = wx.NewId() - self.Bind( wx.EVT_MENU, self.OnConnect, id=self.connectID ) - self.Bind( wx.EVT_MENU, self.OnDisconnect, id=self.disconnectID ) + self.Bind(wx.EVT_MENU, self.OnConnect, id=self.connectID) + self.Bind(wx.EVT_MENU, self.OnDisconnect, id=self.disconnectID) menu = wx.Menu() - if not hasattr( self.selectedcard, 'connection' ): - menu.Append( self.connectID, "Connect" ) + if not hasattr(self.selectedcard, 'connection'): + menu.Append(self.connectID, "Connect") else: - menu.Append( self.disconnectID, "Disconnect" ) - self.PopupMenu( menu ) + menu.Append(self.disconnectID, "Disconnect") + self.PopupMenu(menu) menu.Destroy() - def OnConnect( self, event ): - if isinstance( self.selectedcard, smartcard.Card.Card ): - self.ActivateCard( self.selectedcard ) + def OnConnect(self, event): + if isinstance(self.selectedcard, smartcard.Card.Card): + self.ActivateCard(self.selectedcard) - def OnDisconnect( self, event ): - if isinstance( self.selectedcard, smartcard.Card.Card ): - self.DeactivateCard( self.selectedcard ) + def OnDisconnect(self, event): + if isinstance(self.selectedcard, smartcard.Card.Card): + self.DeactivateCard(self.selectedcard) - def OnSelectCard( self, event ): + def OnSelectCard(self, event): """Called when the user selects a card in the tree.""" item = event.GetItem() if item: - itemdata = self.readertreepanel.cardtreectrl.GetItemPyData( item ) - if isinstance( itemdata, smartcard.Card.Card ): - self.dialogpanel.OnSelectCard( itemdata ) + itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item) + if isinstance(itemdata, smartcard.Card.Card): + self.dialogpanel.OnSelectCard(itemdata) else: - self.dialogpanel.OnDeselectCard( itemdata ) + self.dialogpanel.OnDeselectCard(itemdata) - def OnSelectReader( self, event ): + def OnSelectReader(self, event): """Called when the user selects a reader in the tree.""" item = event.GetItem() if item: - itemdata = self.readertreepanel.readertreectrl.GetItemPyData( item ) - if isinstance( itemdata, smartcard.Card.Card ): - self.dialogpanel.OnSelectCard( itemdata ) - elif isinstance( itemdata, smartcard.reader.Reader.Reader ): - self.dialogpanel.OnSelectReader( itemdata ) + itemdata = self.readertreepanel.readertreectrl.GetItemPyData(item) + if isinstance(itemdata, smartcard.Card.Card): + self.dialogpanel.OnSelectCard(itemdata) + elif isinstance(itemdata, smartcard.reader.Reader.Reader): + self.dialogpanel.OnSelectReader(itemdata) else: - self.dialogpanel.OnDeselectCard( itemdata ) + self.dialogpanel.OnDeselectCard(itemdata) class SimpleSCardAppFrame(wx.Frame): """The main frame of the simple smartcard application.""" - def __init__( self, + + def __init__(self, appname, apppanelclass, appstyle, appicon, - pos=(-1,-1), - size=(-1,-1), - ): + pos=(-1, -1), + size=(-1, -1), + ): """ Constructor. Creates the frame with two panels: the left-hand panel is holding the smartcard and/or reader tree @@ -239,7 +238,7 @@ appname: name of the application apppanelclass: the class of the panel to instantiate in the SimpleSCardAppFrame - appstyle: a combination of the following styles (bitwise or | ) + appstyle: a combination of the following styles (bitwise or |) TR_SMARTCARD: display a smartcard tree panel TR_READER: display a reader tree panel TB_SMARTCARD: display a smartcard toolbar @@ -250,45 +249,45 @@ size: the application window size as a (x,y) tuple; default is (-1,-1) style: the frame wx.Frame style """ - wx.Frame.__init__( self, + wx.Frame.__init__(self, None, wxID_SIMPLESCARDAPP_FRAME, appname, pos=pos, size=size, - style=wx.DEFAULT_FRAME_STYLE ) + style=wx.DEFAULT_FRAME_STYLE) if appicon: - _icon = wx.Icon( appicon, wx.BITMAP_TYPE_ICO ) + _icon = wx.Icon(appicon, wx.BITMAP_TYPE_ICO) self.SetIcon(_icon) - elif os.path.exists( smartcard.wx.ICO_SMARTCARD ): - _icon = wx.Icon( smartcard.wx.ICO_SMARTCARD, wx.BITMAP_TYPE_ICO ) + elif os.path.exists(smartcard.wx.ICO_SMARTCARD): + _icon = wx.Icon(smartcard.wx.ICO_SMARTCARD, wx.BITMAP_TYPE_ICO) self.SetIcon(_icon) - boxsizer = wx.BoxSizer( wx.VERTICAL ) - self.treeuserpanel = TreeAndUserPanelPanel( self, apppanelclass, appstyle ) - boxsizer.Add( self.treeuserpanel, 3, wx.EXPAND | wx.ALL ) + boxsizer = wx.BoxSizer(wx.VERTICAL) + self.treeuserpanel = TreeAndUserPanelPanel(self, apppanelclass, appstyle) + boxsizer.Add(self.treeuserpanel, 3, wx.EXPAND | wx.ALL) # create a toolbar if required if appstyle & smartcard.wx.SimpleSCardApp.TB_SMARTCARD: - self.toolbar = ReaderToolbar.ReaderToolbar( self ) - self.SetToolBar( self.toolbar ) + self.toolbar = ReaderToolbar.ReaderToolbar(self) + self.SetToolBar(self.toolbar) else: - self.toolbar=None + self.toolbar = None # create an apdu tracer console if required if appstyle & smartcard.wx.SimpleSCardApp.PANEL_APDUTRACER: - self.apdutracerpanel = APDUTracerPanel.APDUTracerPanel( self ) - boxsizer.Add( self.apdutracerpanel, 1, wx.EXPAND | wx.ALL ) + self.apdutracerpanel = APDUTracerPanel.APDUTracerPanel(self) + boxsizer.Add(self.apdutracerpanel, 1, wx.EXPAND | wx.ALL) else: - self.apdutracerpanel=None + self.apdutracerpanel = None - self.SetSizer( boxsizer ) - self.SetAutoLayout( True ) + self.SetSizer(boxsizer) + self.SetAutoLayout(True) - self.Bind( wx.EVT_CLOSE, self.OnCloseFrame ) + self.Bind(wx.EVT_CLOSE, self.OnCloseFrame) if appstyle & smartcard.wx.SimpleSCardApp.TB_SMARTCARD: - self.Bind( wx.EVT_COMBOBOX, self.OnReaderComboBox, self.toolbar.readercombobox ) + self.Bind(wx.EVT_COMBOBOX, self.OnReaderComboBox, self.toolbar.readercombobox) def OnCloseFrame(self, evt): """Called when frame is closed, i.e. on wx.EVT_CLOSE""" @@ -299,9 +298,9 @@ self.Close(True) evt.Skip() - def OnReaderComboBox( self, event ): + def OnReaderComboBox(self, event): """Called when the user activates a reader in the toolbar combo box.""" cb = event.GetEventObject() reader = cb.GetClientData(cb.GetSelection()) - if isinstance( reader, smartcard.reader.Reader.Reader ): - self.treeuserpanel.dialogpanel.OnActivateReader( reader ) + if isinstance(reader, smartcard.reader.Reader.Reader): + self.treeuserpanel.dialogpanel.OnActivateReader(reader) Modified: trunk/pyscard/src/smartcard/wx/__init__.py =================================================================== --- trunk/pyscard/src/smartcard/wx/__init__.py 2010-06-06 16:15:48 UTC (rev 439) +++ trunk/pyscard/src/smartcard/wx/__init__.py 2010-06-06 16:28:54 UTC (rev 440) @@ -26,22 +26,23 @@ import os.path import sys + def main_is_frozen(): - return( hasattr( sys, "frozen" ) or hasattr( sys, "importers" ) or imp.is_frozen( "__main__") ) + return(hasattr(sys, "frozen") or hasattr(sys, "importers") or imp.is_frozen("__main__")) -ICO_SMARTCARD=None -ICO_READER=None +ICO_SMARTCARD = None +ICO_READER = None # running from a script, i.e. not running from standalone exe built with py2exe if not main_is_frozen(): - ICO_SMARTCARD = os.path.join( os.path.dirname( __file__ ), 'resources', 'smartcard.ico' ) - ICO_READER = os.path.join( os.path.dirname( __file__ ), 'resources', 'reader.ico' ) + ICO_SMARTCARD = os.path.join(os.path.dirname(__file__), 'resources', 'smartcard.ico') + ICO_READER = os.path.join(os.path.dirname(__file__), 'resources', 'reader.ico') # runing from a standalone exe built with py2exe # resources expected images directory else: - if os.path.exists( os.path.join( "images", 'smartcard.ico' ) ): - ICO_SMARTCARD = os.path.join( "images", 'smartcard.ico' ) - if os.path.exists( os.path.join( "images", 'reader.ico' ) ): - ICO_READER = os.path.join( "images", 'reader.ico' ) + if os.path.exists(os.path.join("images", 'smartcard.ico')): + ICO_SMARTCARD = os.path.join("images", 'smartcard.ico') + if os.path.exists(os.path.join("images", 'reader.ico')): + ICO_READER = os.path.join("images", 'reader.ico') This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 16:15:54
|
Revision: 439 http://pyscard.svn.sourceforge.net/pyscard/?rev=439&view=rev Author: ludov Date: 2010-06-06 16:15:48 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/util/__init__.py Modified: trunk/pyscard/src/smartcard/util/__init__.py =================================================================== --- trunk/pyscard/src/smartcard/util/__init__.py 2010-06-06 16:09:59 UTC (rev 438) +++ trunk/pyscard/src/smartcard/util/__init__.py 2010-06-06 16:15:48 UTC (rev 439) @@ -23,12 +23,13 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ -PACK=1 -HEX=2 -UPPERCASE=4 -COMMA=8 +PACK = 1 +HEX = 2 +UPPERCASE = 4 +COMMA = 8 -def padd( bytelist, length, padding='FF' ): + +def padd(bytelist, length, padding='FF'): """ Padds a byte list with a constant byte value (default is x0FF) bytelist: the byte list to padd length: the total length of the resulting byte list; @@ -37,19 +38,19 @@ returns the padded bytelist example: - padd( toBytes(\"3B 65 00 00 9C 11 01 01 03\"), 16 ) returns [0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] - padd( toBytes(\"3B 65 00 00 9C 11 01 01 03\"), 8 ) returns [0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3 ] + padd(toBytes(\"3B 65 00 00 9C 11 01 01 03\"), 16) returns [0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] + padd(toBytes(\"3B 65 00 00 9C 11 01 01 03\"), 8) returns [0x3B, 0x65, 0, 0, 0x9C, 0x11, 1, 1, 3 ] """ - if len( bytelist ) < length: - for index in range(length-len(bytelist)): - bytelist.append(eval('0x'+padding)) + if len(bytelist) < length: + for index in range(length - len(bytelist)): + bytelist.append(eval('0x' + padding)) return bytelist -def toASCIIBytes( stringtoconvert ): +def toASCIIBytes(stringtoconvert): """Returns a list of ASCII bytes from a string. stringtoconvert: the string to convert into a byte list @@ -59,13 +60,13 @@ toASCIIBytes() is the reverse of toASCIIString() example: - toASCIIBytes( "Number 101" ) returns[ 0x4E, 0x75, 0x6D, 0x62, 0x65, 0x72, 0x20, 0x31, 0x30, 0x31 ] + toASCIIBytes("Number 101") returns[ 0x4E, 0x75, 0x6D, 0x62, 0x65, 0x72, 0x20, 0x31, 0x30, 0x31 ] """ - return map( ord, list(stringtoconvert) ) + return map(ord, list(stringtoconvert)) -def toASCIIString( bytelist ): +def toASCIIString(bytelist): """Returns a string representing a list of ASCII bytes. bytelist: list of ASCII bytes to convert into a string @@ -76,67 +77,70 @@ example: - toASCIIString( [ 0x4E, 0x75, 0x6D, 0x62, 0x65, 0x72, 0x20, 0x31, 0x30, 0x31 ] ) returns "Number 101" ) + toASCIIString([ 0x4E, 0x75, 0x6D, 0x62, 0x65, 0x72, 0x20, 0x31, 0x30, 0x31 ]) returns "Number 101") """ - return ''.join( map( chr, bytelist ) ) + return ''.join(map(chr, bytelist)) -def toBytes( bytestring ): + +def toBytes(bytestring): """Returns a list of bytes from a byte string bytestring: a byte string of the format \"3B 65 00 00 9C 11 01 01 03\" or \"3B6500009C11010103\" or \"3B6500 009C1101 0103\" """ from struct import unpack import re - packedstring = ''.join( re.split( '\W+', bytestring ) ) + packedstring = ''.join(re.split('\W+', bytestring)) try: - return reduce( lambda x, y: x+[int(y,16)], unpack( '2s' * (len(packedstring)/2) , packedstring ), [] ) + return reduce(lambda x, y: x + [int(y, 16)], unpack('2s' * (len(packedstring) / 2), packedstring), []) except: raise TypeError, 'not a string representing a list of bytes' """GSM3.38 character conversion table.""" __dic_GSM_3_38__ = { - '@':0x00, # @ At symbol - '\xA3':0x01, # \xA3 Britain pound symbol - '$':0x02, # $ Dollar symbol - chr(0xA5):0x03, # \xA5 Yen symbol - '\xE8':0x04, # \xE8 e accent grave - '\xE9':0x05, # \xE9 e accent aigu - '\xF9':0x06, # \xF9 u accent grave - chr(0xEC):0x07, # \xEC i accent grave - chr(0xF2):0x08, # \xF2 o accent grave - chr(0xC7):0x09, # \xC7 C majuscule cedille - chr(0x0A):0x0A, # LF Line Feed - chr(0xD8):0x0B, # \xD8 O majuscule barr\xE9 - chr(0xF8):0x0C, # \xF8 o minuscule barr\xE9 - chr(0x0D):0x0D, # CR Carriage Return - chr(0xC5):0x0E, # \xC5 Angstroem majuscule - chr(0xE5):0x0F, # \xE5 Angstroem minuscule - '_':0x11, # underscore - chr(0xC6):0x1C, # \xC6 majuscule ae - chr(0xE6):0x1D, # \xE6 minuscule ae - chr(0xDF):0x1E, # \xDF s dur allemand - chr(0xC9):0x1F, # \xC9 majuscule \xE9 - ' ':0x20, '!':0x21, - '\"':0x22, # guillemet - '#':0x23, - '\xA4':0x24, # \xA4 carr\xE9 - chr(0xA1):0x40, # \xA1 point d'exclamation renvers\xE9 - chr(0xC4):0x5B, # \xC4 majuscule A trema - chr(0xE4):0x7B, # \xE4 minuscule a trema - chr(0xD6):0x5C, # \xD6 majuscule O trema - chr(0xF6):0x7C, # \xF6 minuscule o trema - chr(0xD1):0x5D, # \xD1 majuscule N tilda espagnol - chr(0xF1):0x7D, # \xF1 minuscule n tilda espagnol - chr(0xDC):0x5E, # \xDC majuscule U trema - chr(0xFC):0x7E, # \xFC minuscule u trema - chr(0xA7):0x5F, # \xA7 signe paragraphe - chr(0xBF):0x60, # \xBF point interrogation renvers\xE9 - '\xE0':0x7F # a accent grave + '@': 0x00, # @ At symbol + '\xA3': 0x01, # \xA3 Britain pound symbol + '$': 0x02, # $ Dollar symbol + chr(0xA5): 0x03, # \xA5 Yen symbol + '\xE8': 0x04, # \xE8 e accent grave + '\xE9': 0x05, # \xE9 e accent aigu + '\xF9': 0x06, # \xF9 u accent grave + chr(0xEC): 0x07, # \xEC i accent grave + chr(0xF2): 0x08, # \xF2 o accent grave + chr(0xC7): 0x09, # \xC7 C majuscule cedille + chr(0x0A): 0x0A, # LF Line Feed + chr(0xD8): 0x0B, # \xD8 O majuscule barr\xE9 + chr(0xF8): 0x0C, # \xF8 o minuscule barr\xE9 + chr(0x0D): 0x0D, # CR Carriage Return + chr(0xC5): 0x0E, # \xC5 Angstroem majuscule + chr(0xE5): 0x0F, # \xE5 Angstroem minuscule + '_': 0x11, # underscore + chr(0xC6): 0x1C, # \xC6 majuscule ae + chr(0xE6): 0x1D, # \xE6 minuscule ae + chr(0xDF): 0x1E, # \xDF s dur allemand + chr(0xC9): 0x1F, # \xC9 majuscule \xE9 + ' ': 0x20, + '!': 0x21, + '\"': 0x22, # guillemet + '#': 0x23, + '\xA4': 0x24, # \xA4 carr\xE9 + chr(0xA1): 0x40, # \xA1 point d'exclamation renvers\xE9 + chr(0xC4): 0x5B, # \xC4 majuscule A trema + chr(0xE4): 0x7B, # \xE4 minuscule a trema + chr(0xD6): 0x5C, # \xD6 majuscule O trema + chr(0xF6): 0x7C, # \xF6 minuscule o trema + chr(0xD1): 0x5D, # \xD1 majuscule N tilda espagnol + chr(0xF1): 0x7D, # \xF1 minuscule n tilda espagnol + chr(0xDC): 0x5E, # \xDC majuscule U trema + chr(0xFC): 0x7E, # \xFC minuscule u trema + chr(0xA7): 0x5F, # \xA7 signe paragraphe + chr(0xBF): 0x60, # \xBF point interrogation renvers\xE9 + '\xE0': 0x7F # a accent grave } -def toGSM3_38Bytes( stringtoconvert ): + +def toGSM3_38Bytes(stringtoconvert): """Returns a list of bytes from a string using GSM 3.38 conversion table. stringtoconvert: string to convert @@ -144,10 +148,10 @@ returns a list of bytes example: - toGSM3_38Bytes( "@\xF9Pascal" ) returns [ 0x00, 0x06, 0x50, 0x61, 0x73, 0x63, 0x61, 0x6C ] + toGSM3_38Bytes("@\xF9Pascal") returns [ 0x00, 0x06, 0x50, 0x61, 0x73, 0x63, 0x61, 0x6C ] """ - bytes =[] + bytes = [] for char in stringtoconvert: if ((char >= "%") and (char <= "?")): bytes.append(ord(char)) @@ -160,7 +164,7 @@ return bytes -def toHexString( bytes=[], format=0 ): +def toHexString(bytes=[], format=0): """Returns an hex string representing bytes bytes: a list of bytes to stringify, e.g. [59, 22, 148, 32, 2, 1, 0, 0, 13] @@ -173,16 +177,16 @@ example: bytes = [ 0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03 ] - toHexString( bytes ) returns 3B 65 00 00 9C 11 01 01 03 + toHexString(bytes) returns 3B 65 00 00 9C 11 01 01 03 - toHexString( bytes, COMMA ) returns 3B, 65, 00, 00, 9C, 11, 01, 01, 03 - toHexString( bytes, HEX ) returns 0x3B 0x65 0x00 0x00 0x9C 0x11 0x01 0x01 0x03 - toHexString( bytes, HEX | COMMA ) returns 0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03 + toHexString(bytes, COMMA) returns 3B, 65, 00, 00, 9C, 11, 01, 01, 03 + toHexString(bytes, HEX) returns 0x3B 0x65 0x00 0x00 0x9C 0x11 0x01 0x01 0x03 + toHexString(bytes, HEX | COMMA) returns 0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03 - toHexString( bytes, PACK ) returns 3B6500009C11010103 + toHexString(bytes, PACK) returns 3B6500009C11010103 - toHexString( bytes, HEX | UPPERCASE ) returns 0X3B 0X65 0X00 0X00 0X9C 0X11 0X01 0X01 0X03 - toHexString( bytes, HEX | UPPERCASE | COMMA) returns 0X3B, 0X65, 0X00, 0X00, 0X9C, 0X11, 0X01, 0X01, 0X03 + toHexString(bytes, HEX | UPPERCASE) returns 0X3B 0X65 0X00 0X00 0X9C 0X11 0X01 0X01 0X03 + toHexString(bytes, HEX | UPPERCASE | COMMA) returns 0X3B, 0X65, 0X00, 0X00, 0X9C, 0X11, 0X01, 0X01, 0X03 """ from string import rstrip @@ -193,36 +197,40 @@ if type(bytes) is not list: raise TypeError, 'not a list of bytes' - if bytes==None or bytes==[]: + if bytes == None or bytes == []: return "" else: - pformat="%-0.2X" + pformat = "%-0.2X" if COMMA & format: - pformat = pformat+"," - pformat = pformat+" " + pformat = pformat + "," + pformat = pformat + " " if PACK & format: - pformat=rstrip( pformat ) + pformat = rstrip(pformat) if HEX & format: if UPPERCASE & format: - pformat = "0X"+pformat + pformat = "0X" + pformat else: - pformat = "0x"+pformat - return rstrip(rstrip(reduce( lambda a, b: a+pformat % ((b+256)%256), [""] + bytes )),',') + pformat = "0x" + pformat + return rstrip(rstrip(reduce(lambda a, b: a + pformat % ((b + 256) % 256), [""] + bytes)), ',') -def HexListToBinString( hexlist ): - binstring="" + +def HexListToBinString(hexlist): + binstring = "" for byte in hexlist: - binstring= binstring + chr( eval( '0x%x' % byte ) ) + binstring = binstring + chr(eval('0x%x' % byte)) return binstring -def BinStringToHexList( binstring ): - hexlist=[] + +def BinStringToHexList(binstring): + hexlist = [] for byte in binstring: - hexlist= hexlist + [ ord(byte) ] + hexlist = hexlist + [ord(byte)] return hexlist -def hl2bs( hexlist ): - return HexListToBinString( hexlist ) -def bs2hl( binstring ): - return BinStringToHexList( binstring ) +def hl2bs(hexlist): + return HexListToBinString(hexlist) + + +def bs2hl(binstring): + return BinStringToHexList(binstring) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 16:10:05
|
Revision: 438 http://pyscard.svn.sourceforge.net/pyscard/?rev=438&view=rev Author: ludov Date: 2010-06-06 16:09:59 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/sw/ErrorChecker.py trunk/pyscard/src/smartcard/sw/ErrorCheckingChain.py trunk/pyscard/src/smartcard/sw/ISO7816_4ErrorChecker.py trunk/pyscard/src/smartcard/sw/ISO7816_4_SW1ErrorChecker.py trunk/pyscard/src/smartcard/sw/ISO7816_8ErrorChecker.py trunk/pyscard/src/smartcard/sw/ISO7816_9ErrorChecker.py trunk/pyscard/src/smartcard/sw/SWExceptions.py trunk/pyscard/src/smartcard/sw/op21_ErrorChecker.py Modified: trunk/pyscard/src/smartcard/sw/ErrorChecker.py =================================================================== --- trunk/pyscard/src/smartcard/sw/ErrorChecker.py 2010-06-06 15:55:46 UTC (rev 437) +++ trunk/pyscard/src/smartcard/sw/ErrorChecker.py 2010-06-06 16:09:59 UTC (rev 438) @@ -22,18 +22,21 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ + class ErrorChecker: """Base class for status word error checking strategies. - Error checking strategies are chained into an ErrorCheckingChain to implement - a Chain of Responsibility. Each strategy in the chain is called until an error - is detected. The strategy raises a smartcard.sw.SWException exception when an - error is detected. + Error checking strategies are chained into an ErrorCheckingChain to + implement a Chain of Responsibility. Each strategy in the chain is + called until an error is detected. The strategy raises a + smartcard.sw.SWException exception when an error is detected. - Implementation derived from Bruce Eckel, Thinking in Python. The ErrorCheckingChain - implements the Chain Of Responsibility design pattern. + Implementation derived from Bruce Eckel, Thinking in Python. The + ErrorCheckingChain implements the Chain Of Responsibility design + pattern. """ - def __call__( data, sw1, sw2 ): + + def __call__(data, sw1, sw2): """Called to test data, sw1 and sw2 for error. data: apdu response data Modified: trunk/pyscard/src/smartcard/sw/ErrorCheckingChain.py =================================================================== --- trunk/pyscard/src/smartcard/sw/ErrorCheckingChain.py 2010-06-06 15:55:46 UTC (rev 437) +++ trunk/pyscard/src/smartcard/sw/ErrorCheckingChain.py 2010-06-06 16:09:59 UTC (rev 438) @@ -26,53 +26,57 @@ class ErrorCheckingChain: - """The error checking chain is a list of response apdu status word (sw1, sw2) - error check strategies. Each strategy in the chain is called until an error is - detected. A smartcard.sw.SWException exception is raised when an error is - detected. No exception is raised if no error is detected. + """The error checking chain is a list of response apdu status word + (sw1, sw2) error check strategies. Each strategy in the chain is + called until an error is detected. A smartcard.sw.SWException + exception is raised when an error is detected. No exception is + raised if no error is detected. - Implementation derived from Bruce Eckel, Thinking in Python. The ErrorCheckingChain - implements the Chain Of Responsibility design pattern. + Implementation derived from Bruce Eckel, Thinking in Python. The + ErrorCheckingChain implements the Chain Of Responsibility design + pattern. """ - def __init__( self, chain, strategy ): + + def __init__(self, chain, strategy): """constructor. Appends a strategy to the ErrorCheckingChain chain.""" self.strategy = strategy self.chain = chain self.chain.append(self) - self.excludes=[] + self.excludes = [] - def next( self ): + def next(self): """Returns next error checking strategy.""" # Where this link is in the chain: location = self.chain.index(self) if not self.end(): return self.chain[location + 1] - def addFilterException( self, exClass ): + def addFilterException(self, exClass): """Add an exception filter to the error checking chain. - exClass: the exception to exclude, e.g. smartcard.sw.SWExceptions.WarningProcessingException - A filtered exception will not be raised when the sw1,sw2 conditions that would raise - the excption are met. + exClass: the exception to exclude, e.g. + smartcard.sw.SWExceptions.WarningProcessingException A filtered + exception will not be raised when the sw1,sw2 conditions that + would raise the excption are met. """ - self.excludes.append( exClass ) + + self.excludes.append(exClass) if self.end(): return - self.next().addFilterException( exClass ) + self.next().addFilterException(exClass) - def end( self ): + def end(self): """Returns True if this is the end of the error checking strategy chain.""" return (self.chain.index(self) + 1 >= len(self.chain)) - - def __call__( self, data, sw1, sw2 ): + def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error on the chain.""" try: - self.strategy( data, sw1, sw2 ) + self.strategy(data, sw1, sw2) except: # if exception is filtered, return for exception in self.excludes: - if exception==exc_info()[0]: + if exception == exc_info()[0]: return # otherwise reraise exception raise @@ -80,4 +84,4 @@ # if not done, call next strategy if self.end(): return - return self.next()( data, sw1, sw2 ) + return self.next()(data, sw1, sw2) Modified: trunk/pyscard/src/smartcard/sw/ISO7816_4ErrorChecker.py =================================================================== --- trunk/pyscard/src/smartcard/sw/ISO7816_4ErrorChecker.py 2010-06-06 15:55:46 UTC (rev 437) +++ trunk/pyscard/src/smartcard/sw/ISO7816_4ErrorChecker.py 2010-06-06 16:09:59 UTC (rev 438) @@ -26,80 +26,80 @@ import smartcard.sw.SWExceptions iso7816_4SW = { - 0x62:( smartcard.sw.SWExceptions.WarningProcessingException, - { 0x00:"Response padded/ More APDU commands expected", - 0x81:"Part of returned data may be corrupted", - 0x82:"End of file/record reached before reading Le bytes", - 0x83:"File invalidated", - 0x84:"FCI not correctly formatted", - 0xFF:"Correct execution, response padded" } ), + 0x62: (smartcard.sw.SWExceptions.WarningProcessingException, + {0x00: "Response padded/ More APDU commands expected", + 0x81: "Part of returned data may be corrupted", + 0x82: "End of file/record reached before reading Le bytes", + 0x83: "File invalidated", + 0x84: "FCI not correctly formatted", + 0xFF: "Correct execution, response padded"}), - 0x63:( smartcard.sw.SWExceptions.WarningProcessingException, - { 0x00:"Authentication failed", - 0x81:"File filled up by the last write", - 0xC0:"PIN verification failed. 0 tries remaining before blocking PIN", - 0xC1:"PIN verification failed. 1 tries remaining before blocking PIN", - 0xC2:"PIN verification failed. 2 tries remaining before blocking PIN", - 0xC3:"PIN verification failed. 3 tries remaining before blocking PIN", - 0xC4:"PIN verification failed. 4 tries remaining before blocking PIN", - 0xC5:"PIN verification failed. 5 tries remaining before blocking PIN", - 0xC6:"PIN verification failed. 6 tries remaining before blocking PIN", - 0xC7:"PIN verification failed. 7 tries remaining before blocking PIN", - 0xC8:"PIN verification failed. 8 tries remaining before blocking PIN", - 0xC9:"PIN verification failed. 9 tries remaining before blocking PIN", - 0xCA:"PIN verification failed. 10 tries remaining before blocking PIN", - 0xCB:"PIN verification failed. 11 tries remaining before blocking PIN", - 0xCC:"PIN verification failed. 12 tries remaining before blocking PIN", - 0xCD:"PIN verification failed. 13 tries remaining before blocking PIN", - 0xCE:"PIN verification failed. 14 tries remaining before blocking PIN", - 0xCF:"PIN verification failed. 15 tries remaining before blocking PIN" } ), + 0x63: (smartcard.sw.SWExceptions.WarningProcessingException, + {0x00: "Authentication failed", + 0x81: "File filled up by the last write", + 0xC0: "PIN verification failed. 0 tries remaining before blocking PIN", + 0xC1: "PIN verification failed. 1 tries remaining before blocking PIN", + 0xC2: "PIN verification failed. 2 tries remaining before blocking PIN", + 0xC3: "PIN verification failed. 3 tries remaining before blocking PIN", + 0xC4: "PIN verification failed. 4 tries remaining before blocking PIN", + 0xC5: "PIN verification failed. 5 tries remaining before blocking PIN", + 0xC6: "PIN verification failed. 6 tries remaining before blocking PIN", + 0xC7: "PIN verification failed. 7 tries remaining before blocking PIN", + 0xC8: "PIN verification failed. 8 tries remaining before blocking PIN", + 0xC9: "PIN verification failed. 9 tries remaining before blocking PIN", + 0xCA: "PIN verification failed. 10 tries remaining before blocking PIN", + 0xCB: "PIN verification failed. 11 tries remaining before blocking PIN", + 0xCC: "PIN verification failed. 12 tries remaining before blocking PIN", + 0xCD: "PIN verification failed. 13 tries remaining before blocking PIN", + 0xCE: "PIN verification failed. 14 tries remaining before blocking PIN", + 0xCF: "PIN verification failed. 15 tries remaining before blocking PIN"}), - 0x64:( smartcard.sw.SWExceptions.ExecutionErrorException, - { 0x00:"Integrity error detected in EEPROM" } ), + 0x64: (smartcard.sw.SWExceptions.ExecutionErrorException, + {0x00: "Integrity error detected in EEPROM"}), - 0x67:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x00:"Wrong length in Lc" } ), + 0x67: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x00: "Wrong length in Lc"}), - 0x68:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x81:"Logical channel not supported", - 0x82:"Secure messaging not supported" } ), + 0x68: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x81: "Logical channel not supported", + 0x82: "Secure messaging not supported"}), - 0x69:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x81:"Command incompatible with file structure.", - 0x82:"Security status not satisfied", - 0x83:"Authentification method blocked", - 0x84:"Referenced data invalid", - 0x85:"Conditions of use not satisfied", - 0x86:"Command not allowed (no current EF)", - 0x87:"Secure messaging data object missing.", - 0x88:"Secure messaging data object incorrect" } ), + 0x69: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x81: "Command incompatible with file structure.", + 0x82: "Security status not satisfied", + 0x83: "Authentification method blocked", + 0x84: "Referenced data invalid", + 0x85: "Conditions of use not satisfied", + 0x86: "Command not allowed (no current EF)", + 0x87: "Secure messaging data object missing.", + 0x88: "Secure messaging data object incorrect"}), - 0x6A:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x80:"Incorrect parameters in the data field", - 0x81:"Function not supported", - 0x82:"File not found", - 0x83:"Record not found", - 0x84:"Not enough memory space in the file", - 0x85:"Lc inconsistent with TLV structure", - 0x86:"Incorrect parameters P1-P2", - 0x87:"Lc is inconsistent with P1-P2", - 0x88:"Referenced data not found" } ), + 0x6A: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x80: "Incorrect parameters in the data field", + 0x81: "Function not supported", + 0x82: "File not found", + 0x83: "Record not found", + 0x84: "Not enough memory space in the file", + 0x85: "Lc inconsistent with TLV structure", + 0x86: "Incorrect parameters P1-P2", + 0x87: "Lc is inconsistent with P1-P2", + 0x88: "Referenced data not found"}), - 0x6B:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x00:"Incorrect parameters P1-P2" } ), + 0x6B: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x00: "Incorrect parameters P1-P2"}), - 0x6D:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x00:"Instruction (INS) not supported" } ), + 0x6D: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x00: "Instruction (INS) not supported"}), - 0x6E:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x00:"Class (CLA) not supported" } ), + 0x6E: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x00: "Class (CLA) not supported"}), - 0x6F:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x00:"Fatal error" } ), + 0x6F: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x00: "Fatal error"}), } -class ISO7816_4ErrorChecker( ErrorChecker ): +class ISO7816_4ErrorChecker(ErrorChecker): """ISO7816-4 error checking strategy. This strategy raises the following exceptions: @@ -130,30 +130,32 @@ 6b any except 00 - Use another checker in the error checking chain, e.g., the ISO7816_4SW1ErrorChecker, - to raise exceptions on these undefined values. + Use another checker in the error checking chain, e.g., the + ISO7816_4SW1ErrorChecker, to raise exceptions on these undefined + values. """ - def __call__( self, data, sw1, sw2 ): + + def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. data: apdu response data sw1, sw2: apdu data status words Derived classes must raise a smartcard.sw.SWException upon error.""" - if iso7816_4SW.has_key( sw1 ): + if iso7816_4SW.has_key(sw1): exception, sw2dir = iso7816_4SW[sw1] - if type(sw2dir)==type({}): + if type(sw2dir) == type({}): try: message = sw2dir[sw2] - raise exception( data, sw1, sw2, message ) + raise exception(data, sw1, sw2, message) except KeyError: pass if __name__ == '__main__': """Small sample illustrating the use of ISO7816_4ErrorChecker.""" - ecs=ISO7816_4ErrorChecker() - ecs( [], 0x90, 0x00 ) + ecs = ISO7816_4ErrorChecker() + ecs([], 0x90, 0x00) try: - ecs( [], 0x6b, 0x00 ) + ecs([], 0x6b, 0x00) except smartcard.sw.SWExceptions.CheckingErrorException, e: print e, "%x %x" % (e.sw1, e.sw2) Modified: trunk/pyscard/src/smartcard/sw/ISO7816_4_SW1ErrorChecker.py =================================================================== --- trunk/pyscard/src/smartcard/sw/ISO7816_4_SW1ErrorChecker.py 2010-06-06 15:55:46 UTC (rev 437) +++ trunk/pyscard/src/smartcard/sw/ISO7816_4_SW1ErrorChecker.py 2010-06-06 16:09:59 UTC (rev 438) @@ -26,24 +26,24 @@ import smartcard.sw.SWExceptions iso7816_4SW1 = { - 0x62:smartcard.sw.SWExceptions.WarningProcessingException, - 0x63:smartcard.sw.SWExceptions.WarningProcessingException, - 0x64:smartcard.sw.SWExceptions.ExecutionErrorException, - 0x65:smartcard.sw.SWExceptions.ExecutionErrorException, - 0x66:smartcard.sw.SWExceptions.SecurityRelatedException, - 0x67:smartcard.sw.SWExceptions.CheckingErrorException, - 0x68:smartcard.sw.SWExceptions.CheckingErrorException, - 0x69:smartcard.sw.SWExceptions.CheckingErrorException, - 0x6A:smartcard.sw.SWExceptions.CheckingErrorException, - 0x6B:smartcard.sw.SWExceptions.CheckingErrorException, - 0x6C:smartcard.sw.SWExceptions.CheckingErrorException, - 0x6D:smartcard.sw.SWExceptions.CheckingErrorException, - 0x6E:smartcard.sw.SWExceptions.CheckingErrorException, - 0x6F:smartcard.sw.SWExceptions.CheckingErrorException, + 0x62: smartcard.sw.SWExceptions.WarningProcessingException, + 0x63: smartcard.sw.SWExceptions.WarningProcessingException, + 0x64: smartcard.sw.SWExceptions.ExecutionErrorException, + 0x65: smartcard.sw.SWExceptions.ExecutionErrorException, + 0x66: smartcard.sw.SWExceptions.SecurityRelatedException, + 0x67: smartcard.sw.SWExceptions.CheckingErrorException, + 0x68: smartcard.sw.SWExceptions.CheckingErrorException, + 0x69: smartcard.sw.SWExceptions.CheckingErrorException, + 0x6A: smartcard.sw.SWExceptions.CheckingErrorException, + 0x6B: smartcard.sw.SWExceptions.CheckingErrorException, + 0x6C: smartcard.sw.SWExceptions.CheckingErrorException, + 0x6D: smartcard.sw.SWExceptions.CheckingErrorException, + 0x6E: smartcard.sw.SWExceptions.CheckingErrorException, + 0x6F: smartcard.sw.SWExceptions.CheckingErrorException, } -class ISO7816_4_SW1ErrorChecker( ErrorChecker ): +class ISO7816_4_SW1ErrorChecker(ErrorChecker): """ISO7816-4 error checker based on status word sw1 only. This error checker raises the following exceptions: @@ -63,22 +63,23 @@ 6e any CheckingErrorException 6f any CheckingErrorException """ - def __call__( self, data, sw1, sw2 ): + + def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. data: apdu response data sw1, sw2: apdu data status words """ - if iso7816_4SW1.has_key( sw1 ): - exception=iso7816_4SW1[sw1] - raise exception( data, sw1, sw2 ) + if iso7816_4SW1.has_key(sw1): + exception = iso7816_4SW1[sw1] + raise exception(data, sw1, sw2) if __name__ == '__main__': """Small sample illustrating the use of ISO7816_4_SW1ErrorChecker.""" - ecs=ISO7816_4_SW1ErrorChecker() - ecs( [], 0x90, 0x00 ) + ecs = ISO7816_4_SW1ErrorChecker() + ecs([], 0x90, 0x00) try: - ecs( [], 0x66, 0x80 ) + ecs([], 0x66, 0x80) except smartcard.sw.SWExceptions.SecurityRelatedException, e: print e, "%x %x" % (e.sw1, e.sw2) Modified: trunk/pyscard/src/smartcard/sw/ISO7816_8ErrorChecker.py =================================================================== --- trunk/pyscard/src/smartcard/sw/ISO7816_8ErrorChecker.py 2010-06-06 15:55:46 UTC (rev 437) +++ trunk/pyscard/src/smartcard/sw/ISO7816_8ErrorChecker.py 2010-06-06 16:09:59 UTC (rev 438) @@ -26,56 +26,55 @@ import smartcard.sw.SWExceptions iso7816_8SW = { - 0x63:( smartcard.sw.SWExceptions.WarningProcessingException, - { 0x00:"Authentication failed", - 0xC0:"PIN verification failed. 0 retries remaining before blocking PIN", - 0xC1:"PIN verification failed. 1 retries remaining before blocking PIN", - 0xC2:"PIN verification failed. 2 retries remaining before blocking PIN", - 0xC3:"PIN verification failed. 3 retries remaining before blocking PIN", - 0xC4:"PIN verification failed. 4 retries remaining before blocking PIN", - 0xC5:"PIN verification failed. 5 retries remaining before blocking PIN", - 0xC6:"PIN verification failed. 6 retries remaining before blocking PIN", - 0xC7:"PIN verification failed. 7 retries remaining before blocking PIN", - 0xC8:"PIN verification failed. 8 retries remaining before blocking PIN", - 0xC9:"PIN verification failed. 9 retries remaining before blocking PIN", - 0xCA:"PIN verification failed. 10 retries remaining before blocking PIN", - 0xCB:"PIN verification failed. 11 retries remaining before blocking PIN", - 0xCC:"PIN verification failed. 12 retries remaining before blocking PIN", - 0xCD:"PIN verification failed. 13 retries remaining before blocking PIN", - 0xCE:"PIN verification failed. 14 retries remaining before blocking PIN", - 0xCF:"PIN verification failed. 15 retries remaining before blocking PIN"} ), + 0x63: (smartcard.sw.SWExceptions.WarningProcessingException, + {0x00: "Authentication failed", + 0xC0: "PIN verification failed. 0 retries remaining before blocking PIN", + 0xC1: "PIN verification failed. 1 retries remaining before blocking PIN", + 0xC2: "PIN verification failed. 2 retries remaining before blocking PIN", + 0xC3: "PIN verification failed. 3 retries remaining before blocking PIN", + 0xC4: "PIN verification failed. 4 retries remaining before blocking PIN", + 0xC5: "PIN verification failed. 5 retries remaining before blocking PIN", + 0xC6: "PIN verification failed. 6 retries remaining before blocking PIN", + 0xC7: "PIN verification failed. 7 retries remaining before blocking PIN", + 0xC8: "PIN verification failed. 8 retries remaining before blocking PIN", + 0xC9: "PIN verification failed. 9 retries remaining before blocking PIN", + 0xCA: "PIN verification failed. 10 retries remaining before blocking PIN", + 0xCB: "PIN verification failed. 11 retries remaining before blocking PIN", + 0xCC: "PIN verification failed. 12 retries remaining before blocking PIN", + 0xCD: "PIN verification failed. 13 retries remaining before blocking PIN", + 0xCE: "PIN verification failed. 14 retries remaining before blocking PIN", + 0xCF: "PIN verification failed. 15 retries remaining before blocking PIN"}), - 0x65:( smartcard.sw.SWExceptions.ExecutionErrorException, - { 0x81:"Memory failure (unsuccessful changing)" } ), + 0x65: (smartcard.sw.SWExceptions.ExecutionErrorException, + {0x81: "Memory failure (unsuccessful changing)"}), - 0x66:( smartcard.sw.SWExceptions.SecurityRelatedException, - { 0x00:"The environment cannot be set or modified", - 0x87:"Expected SM data objects missing", - 0x88:"SM data objects incorrect" } ), + 0x66: (smartcard.sw.SWExceptions.SecurityRelatedException, + {0x00: "The environment cannot be set or modified", + 0x87: "Expected SM data objects missing", + 0x88: "SM data objects incorrect"}), - 0x67:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x00:"Wrong length (emtpy Lc field)" } ), + 0x67: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x00: "Wrong length (emtpy Lc field)"}), - 0x68:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x83:"Final command expected", - 0x84:"Command chaining not supported" } ), + 0x68: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x83: "Final command expected", + 0x84: "Command chaining not supported"}), - 0x69:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x82:"Security status not satisfied", - 0x83:"Authentification method blocked", - 0x84:"Referenced data invalidated", - 0x85:"Conditions of use not satisfied" } ), + 0x69: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x82: "Security status not satisfied", + 0x83: "Authentification method blocked", + 0x84: "Referenced data invalidated", + 0x85: "Conditions of use not satisfied"}), - 0x6A:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x81:"Function not supported", - 0x82:"File not found", - 0x86:"Incorrect parameters P1-P2", - 0x88:"Referenced data not found" } ), - + 0x6A: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x81: "Function not supported", + 0x82: "File not found", + x86: "Incorrect parameters P1-P2", + 0x88: "Referenced data not found"}), } -class ISO7816_8ErrorChecker( ErrorChecker ): +class ISO7816_8ErrorChecker(ErrorChecker): """ISO7816-8 error checker. This error checker raises the following exceptions: @@ -102,32 +101,34 @@ 67 any except 00 - Use another checker in the error checking chain, e.g., the ISO7816_4SW1ErrorChecker - or ISO7816_4ErrorChecker, to raise exceptions on these undefined values. + Use another checker in the error checking chain, e.g., the + ISO7816_4SW1ErrorChecker or ISO7816_4ErrorChecker, to raise + exceptions on these undefined values. """ - def __call__( self, data, sw1, sw2 ): + + def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. data: apdu response data sw1, sw2: apdu data status words Derived classes must raise a smartcard.sw.SWException upon error.""" - if iso7816_8SW.has_key( sw1 ): + if iso7816_8SW.has_key(sw1): exception, sw2dir = iso7816_8SW[sw1] - if type(sw2dir)==type({}): + if type(sw2dir) == type({}): try: message = sw2dir[sw2] - raise exception( data, sw1, sw2, message ) + raise exception(data, sw1, sw2, message) except KeyError: pass if __name__ == '__main__': """Small sample illustrating the use of ISO7816_8ErrorChecker.""" - ecs=ISO7816_8ErrorChecker() - ecs( [], 0x90, 0x00 ) - ecs( [], 0x6a, 0x83 ) + ecs = ISO7816_8ErrorChecker() + ecs([], 0x90, 0x00) + ecs([], 0x6a, 0x83) try: - ecs( [], 0x66, 0x87 ) + ecs([], 0x66, 0x87) except smartcard.sw.SWExceptions.SecurityRelatedException, e: print e, "%x %x" % (e.sw1, e.sw2) Modified: trunk/pyscard/src/smartcard/sw/ISO7816_9ErrorChecker.py =================================================================== --- trunk/pyscard/src/smartcard/sw/ISO7816_9ErrorChecker.py 2010-06-06 15:55:46 UTC (rev 437) +++ trunk/pyscard/src/smartcard/sw/ISO7816_9ErrorChecker.py 2010-06-06 16:09:59 UTC (rev 438) @@ -26,24 +26,24 @@ import smartcard.sw.SWExceptions iso7816_9SW = { - 0x62:( smartcard.sw.SWExceptions.WarningProcessingException, - { 0x82:"End of file/record reached" } ), + 0x62: (smartcard.sw.SWExceptions.WarningProcessingException, + {0x82: "End of file/record reached"}), - 0x64:( smartcard.sw.SWExceptions.ExecutionErrorException, - { 0x00:"Execution error" } ), + 0x64: (smartcard.sw.SWExceptions.ExecutionErrorException, + {0x00: "Execution error"}), - 0x69:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x82:"Security status not satisfied" } ), + 0x69: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x82: "Security status not satisfied"}), - 0x6A:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x80:"Incorrect parameters in data field", - 0x84:"Not enough memory space", - 0x89:"File already exists", - 0x8A:"DF name already exists" } ), + 0x6A: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x80: "Incorrect parameters in data field", + 0x84: "Not enough memory space", + 0x89: "File already exists", + 0x8A: "DF name already exists"}), } -class ISO7816_9ErrorChecker( ErrorChecker ): +class ISO7816_9ErrorChecker(ErrorChecker): """ISO7816-8 error checker. This error checker raises the following exceptions: @@ -67,32 +67,34 @@ 64 any except 00 - Use another checker in the error checking chain, e.g., the ISO7816_4SW1ErrorChecker or - ISO7816_4ErrorChecker, to raise exceptions on these undefined values. + Use another checker in the error checking chain, e.g., the + ISO7816_4SW1ErrorChecker or ISO7816_4ErrorChecker, to raise + exceptions on these undefined values. """ - def __call__( self, data, sw1, sw2 ): + + def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. data: apdu response data sw1, sw2: apdu data status words Derived classes must raise a smartcard.sw.SWException upon error.""" - if iso7816_9SW.has_key( sw1 ): + if iso7816_9SW.has_key(sw1): exception, sw2dir = iso7816_9SW[sw1] - if type(sw2dir)==type({}): + if type(sw2dir) == type({}): try: message = sw2dir[sw2] - raise exception( data, sw1, sw2, message ) + raise exception(data, sw1, sw2, message) except KeyError: pass if __name__ == '__main__': """Small sample illustrating the use of ISO7816_9ErrorChecker.""" - ecs=ISO7816_9ErrorChecker() - ecs( [], 0x90, 0x00 ) - ecs( [], 0x6a, 0x81 ) + ecs = ISO7816_9ErrorChecker() + ecs([], 0x90, 0x00) + ecs([], 0x6a, 0x81) try: - ecs( [], 0x6A, 0x8A ) + ecs([], 0x6A, 0x8A) except smartcard.sw.SWExceptions.CheckingErrorException, e: print e, "%x %x" % (e.sw1, e.sw2) Modified: trunk/pyscard/src/smartcard/sw/SWExceptions.py =================================================================== --- trunk/pyscard/src/smartcard/sw/SWExceptions.py 2010-06-06 15:55:46 UTC (rev 437) +++ trunk/pyscard/src/smartcard/sw/SWExceptions.py 2010-06-06 16:09:59 UTC (rev 438) @@ -24,6 +24,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ + class SWException: """Base class for status word exceptions. @@ -31,37 +32,47 @@ in the sw1 and sw2 bytes of the response apdu. """ - def __init__( self, data, sw1, sw2, message="" ): + + def __init__(self, data, sw1, sw2, message=""): self.message = message """response apdu data""" self.data = data """response apdu sw1""" - self.sw1=sw1 + self.sw1 = sw1 """response apdu sw2""" - self.sw2=sw2 + self.sw2 = sw2 + def __str__(self): - return repr( 'Status word exception: ' + self.message + '!' ) + return repr('Status word exception: ' + self.message + '!') -class WarningProcessingException( SWException ): + +class WarningProcessingException(SWException): """Raised when a warning processing is detected from sw1, sw2. Examples of warning processing exception: sw1=62 or sw=63 (ISO7816-4).""" - def __init__( self, data, sw1, sw2, message="" ): - SWException.__init__( self, data, sw1, sw2, "warning processing - " + message ) -class ExecutionErrorException( SWException ): + def __init__(self, data, sw1, sw2, message=""): + SWException.__init__(self, data, sw1, sw2, "warning processing - " + message) + + +class ExecutionErrorException(SWException): """Raised when an execution error is detected from sw1, sw2. Examples of execution error: sw1=64 or sw=65 (ISO7816-4).""" - def __init__( self, data, sw1, sw2, message="" ): - SWException.__init__( self, data, sw1, sw2, "execution error - " + message ) -class SecurityRelatedException( SWException ): + def __init__(self, data, sw1, sw2, message=""): + SWException.__init__(self, data, sw1, sw2, "execution error - " + message) + + +class SecurityRelatedException(SWException): """Raised when a security issue is detected from sw1, sw2. Examples of security issue: sw1=66 (ISO7816-4).""" - def __init__( self, data, sw1, sw2, message="" ): - SWException.__init__( self, data, sw1, sw2, "security issue - " + message ) -class CheckingErrorException( SWException ): + def __init__(self, data, sw1, sw2, message=""): + SWException.__init__(self, data, sw1, sw2, "security issue - " + message) + + +class CheckingErrorException(SWException): """Raised when a checking error is detected from sw1, sw2. Examples of checking error: sw1=67 to 6F (ISO781604).""" - def __init__( self, data, sw1, sw2, message="" ): - SWException.__init__( self, data, sw1, sw2, "checking error - " + message ) + + def __init__(self, data, sw1, sw2, message=""): + SWException.__init__(self, data, sw1, sw2, "checking error - " + message) Modified: trunk/pyscard/src/smartcard/sw/op21_ErrorChecker.py =================================================================== --- trunk/pyscard/src/smartcard/sw/op21_ErrorChecker.py 2010-06-06 15:55:46 UTC (rev 437) +++ trunk/pyscard/src/smartcard/sw/op21_ErrorChecker.py 2010-06-06 16:09:59 UTC (rev 438) @@ -26,47 +26,47 @@ import smartcard.sw.SWExceptions op21_SW = { - 0x62:( smartcard.sw.SWExceptions.WarningProcessingException, - { 0x83:"Card life cycle is CARD_LOCKED" } ), + 0x62: (smartcard.sw.SWExceptions.WarningProcessingException, + {0x83: "Card life cycle is CARD_LOCKED"}), - 0x63:( smartcard.sw.SWExceptions.WarningProcessingException, - { 0x00:"Authentication failed" } ), + 0x63: (smartcard.sw.SWExceptions.WarningProcessingException, + {0x00: "Authentication failed"}), - 0x64:( smartcard.sw.SWExceptions.ExecutionErrorException, - { 0x00:"Execution error" } ), + 0x64: (smartcard.sw.SWExceptions.ExecutionErrorException, + {0x00: "Execution error"}), - 0x65:( smartcard.sw.SWExceptions.ExecutionErrorException, - { 0x81:"Memory failure" } ), + 0x65: (smartcard.sw.SWExceptions.ExecutionErrorException, + {0x81: "Memory failure"}), - 0x67:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x00:"Wrong length in Lc" } ), + 0x67: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x00: "Wrong length in Lc"}), - 0x69:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x82:"Security status not satisfied", - 0x85:"Conditions of use not satisfied" } ), + 0x69: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x82: "Security status not satisfied", + 0x85: "Conditions of use not satisfied"}), - 0x6A:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x80:"Incorrect values in command data", - 0x81:"Function not supported", - 0x82:"Application not found", - 0x84:"Not enough memory space", - 0x86:"Incorrect parameters P1-P2", - 0x88:"Referenced data not found", } ), + 0x6A: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x80: "Incorrect values in command data", + 0x81: "Function not supported", + 0x82: "Application not found", + 0x84: "Not enough memory space", + 0x86: "Incorrect parameters P1-P2", + 0x88: "Referenced data not found"}), - 0x6D:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x00:"Instruction not supported" } ), + 0x6D: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x00: "Instruction not supported"}), - 0x6E:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x00:"Class not supported" } ), + 0x6E: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x00: "Class not supported"}), - 0x94:( smartcard.sw.SWExceptions.CheckingErrorException, - { 0x84:"Algorithm not supported", - 0x85:"Invalid key check value" } ), + 0x94: (smartcard.sw.SWExceptions.CheckingErrorException, + {0x84: "Algorithm not supported", + 0x85: "Invalid key check value"}), } -class op21_ErrorChecker( ErrorChecker ): +class op21_ErrorChecker(ErrorChecker): """Open platform 2.1 error checker. This error checker raises the following exceptions: @@ -96,31 +96,33 @@ 64 any except 00 - Use another checker in the error checking chain to raise exceptions on these undefined values. + Use another checker in the error checking chain to raise exceptions + on these undefined values. """ - def __call__( self, data, sw1, sw2 ): + + def __call__(self, data, sw1, sw2): """Called to test data, sw1 and sw2 for error. data: apdu response data sw1, sw2: apdu data status words Derived classes must raise a smartcard.sw.SWException upon error.""" - if op21_SW.has_key( sw1 ): + if op21_SW.has_key(sw1): exception, sw2dir = op21_SW[sw1] - if type(sw2dir)==type({}): + if type(sw2dir) == type({}): try: message = sw2dir[sw2] - raise exception( data, sw1, sw2, message ) + raise exception(data, sw1, sw2, message) except KeyError: pass if __name__ == '__main__': """Small sample illustrating the use of op21_ErrorChecker.""" - ecs=op21_ErrorChecker() - ecs( [], 0x90, 0x00 ) - ecs( [], 0x94, 0x81 ) + ecs = op21_ErrorChecker() + ecs([], 0x90, 0x00) + ecs([], 0x94, 0x81) try: - ecs( [], 0x94, 0x84 ) + ecs([], 0x94, 0x84) except smartcard.sw.SWExceptions.CheckingErrorException, e: print e, "%x %x" % (e.sw1, e.sw2) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 15:55:52
|
Revision: 437 http://pyscard.svn.sourceforge.net/pyscard/?rev=437&view=rev Author: ludov Date: 2010-06-06 15:55:46 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/reader/Reader.py trunk/pyscard/src/smartcard/reader/ReaderFactory.py trunk/pyscard/src/smartcard/reader/ReaderGroups.py Modified: trunk/pyscard/src/smartcard/reader/Reader.py =================================================================== --- trunk/pyscard/src/smartcard/reader/Reader.py 2010-06-06 15:52:13 UTC (rev 436) +++ trunk/pyscard/src/smartcard/reader/Reader.py 2010-06-06 15:55:46 UTC (rev 437) @@ -22,6 +22,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ + class Reader: """Reader abstract class. @@ -30,33 +31,34 @@ Known subclasses: PCSCReader """ - def __init__( self, readername ): + + def __init__(self, readername): """Constructs a new reader and store readername.""" - self.name=readername + self.name = readername - def addtoreadergroup( self, groupname ): + def addtoreadergroup(self, groupname): """Add reader to a reader group.""" pass - def removefromreadergroup( self, groupname ): + def removefromreadergroup(self, groupname): """Remove reader from a reader group.""" pass - def createConnection( self ): + def createConnection(self): """Returns a card connection thru reader.""" pass - def __eq__( self, other ): + def __eq__(self, other): """Returns 0 if self==other (same name).""" - if type(other)==type(self): - return self.name==other.name + if type(other) == type(self): + return self.name == other.name else: return 1 - def __repr__( self ): + def __repr__(self): """Returns card reader name string for `object` calls.""" return "'%s'" % self.name - def __str__( self ): + def __str__(self): """Returns card reader name string for str(object) calls.""" return self.name Modified: trunk/pyscard/src/smartcard/reader/ReaderFactory.py =================================================================== --- trunk/pyscard/src/smartcard/reader/ReaderFactory.py 2010-06-06 15:52:13 UTC (rev 436) +++ trunk/pyscard/src/smartcard/reader/ReaderFactory.py 2010-06-06 15:55:46 UTC (rev 437) @@ -32,17 +32,19 @@ from smartcard.ClassLoader import get_class + class ReaderFactory: """Class to create readers from reader type id.""" factories = {} - def addFactory( id, ReaderFactory ): + + def addFactory(id, ReaderFactory): """Static method to add a ReaderFactory associated to a reader id.""" ReaderFactory.factories.put[id] = ReaderFactory addFactory = staticmethod(addFactory) # A Template Method: - def createReader( clazz, readername ): + def createReader(clazz, readername): """Static method to create a reader from a reader clazz. module: the python module that contains the reader class @@ -50,6 +52,6 @@ readername: the reader name """ if not ReaderFactory.factories.has_key(clazz): - ReaderFactory.factories[clazz] = get_class( clazz ).Factory() - return ReaderFactory.factories[clazz].create( readername ) + ReaderFactory.factories[clazz] = get_class(clazz).Factory() + return ReaderFactory.factories[clazz].create(readername) createReader = staticmethod(createReader) Modified: trunk/pyscard/src/smartcard/reader/ReaderGroups.py =================================================================== --- trunk/pyscard/src/smartcard/reader/ReaderGroups.py 2010-06-06 15:52:13 UTC (rev 436) +++ trunk/pyscard/src/smartcard/reader/ReaderGroups.py 2010-06-06 15:55:46 UTC (rev 437) @@ -25,16 +25,21 @@ from smartcard.Exceptions import SmartcardException from smartcard.ulist import ulist + class BadReaderGroupException(SmartcardException): """Raised when trying to add an invalid reader group.""" - def __init__( self ): - SmartcardException.__init__( self, 'Invalid reader group' ) + def __init__(self): + SmartcardException.__init__(self, 'Invalid reader group') + + class DeleteSCardDefaultReaderGroupException(SmartcardException): """Raised when trying to delete SCard$DefaultReaders reader group.""" - def __init__( self ): - SmartcardException.__init__( self, 'SCard$DefaultReaders cannot be deleted' ) + def __init__(self): + SmartcardException.__init__(self, 'SCard$DefaultReaders cannot be deleted') + + class innerreadergroups(ulist): """Smartcard readers groups private class. @@ -42,49 +47,49 @@ instance of this class. """ - def __init__(self, initlist=None ): + def __init__(self, initlist=None): """Retrieve and store list of reader groups""" - if None==initlist: - initlist=self.getreadergroups() - if None!=initlist: - ulist.__init__(self, initlist ) - self.unremovablegroups=[] + if None == initlist: + initlist = self.getreadergroups() + if None != initlist: + ulist.__init__(self, initlist) + self.unremovablegroups = [] - - def __onadditem__( self, item ): + def __onadditem__(self, item): """Called when a reader group is added.""" - self.addreadergroup( item ) + self.addreadergroup(item) - def __onremoveitem__( self, item ): + def __onremoveitem__(self, item): """Called when a reader group is added.""" - self.removereadergroup( item ) + self.removereadergroup(item) # # abstract methods implemented in subclasses # - def getreadergroups( self ): + def getreadergroups(self): """Returns the list of smartcard reader groups.""" return [] - def addreadergroup( self, newgroup ): + def addreadergroup(self, newgroup): """Add a reader group""" - if not isinstance( newgroup, type("") ): + if not isinstance(newgroup, type("")): raise BadReaderGroupException - def removereadergroup( self, group ): + def removereadergroup(self, group): """Remove a reader group""" - if not isinstance( group, type("") ): + if not isinstance(group, type("")): raise BadReaderGroupException - def addreadertogroup( self, readername, groupname ): + def addreadertogroup(self, readername, groupname): """Add a reader to a reader group""" pass - def removereaderfromgroup( self, readername, groupname ): + def removereaderfromgroup(self, readername, groupname): """Remove a reader from a reader group""" pass + class readergroups: """ReadersGroups organizes smart card reader as groups.""" @@ -92,11 +97,13 @@ instance = None """Constructor: create a single instance of __readergroups on first call""" - def __init__(self, initlist=None ): - if None==readergroups.instance: - readergroups.instance = innerreadergroups( initlist ) + def __init__(self, initlist=None): + if None == readergroups.instance: + readergroups.instance = innerreadergroups(initlist) + """All operators redirected to inner class.""" + def __getattr__(self, name): return getattr(self.instance, name) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 15:52:19
|
Revision: 436 http://pyscard.svn.sourceforge.net/pyscard/?rev=436&view=rev Author: ludov Date: 2010-06-06 15:52:13 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/pcsc/PCSCReaderGroups.py trunk/pyscard/src/smartcard/pcsc/__init__.py Modified: trunk/pyscard/src/smartcard/pcsc/PCSCReaderGroups.py =================================================================== --- trunk/pyscard/src/smartcard/pcsc/PCSCReaderGroups.py 2010-06-06 15:49:58 UTC (rev 435) +++ trunk/pyscard/src/smartcard/pcsc/PCSCReaderGroups.py 2010-06-06 15:52:13 UTC (rev 436) @@ -48,13 +48,13 @@ innerreadergroups.getreadergroups(self) hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER) - if hresult!=0: + if hresult != 0: raise EstablishContextException(hresult) hresult, readers = SCardListReaderGroups(hcontext) - if hresult!=0: + if hresult != 0: raise ListReadersException(hresult) hresult = SCardReleaseContext(hcontext) - if hresult!=0: + if hresult != 0: raise ReleaseContextException(hresult) return readers Modified: trunk/pyscard/src/smartcard/pcsc/__init__.py =================================================================== --- trunk/pyscard/src/smartcard/pcsc/__init__.py 2010-06-06 15:49:58 UTC (rev 435) +++ trunk/pyscard/src/smartcard/pcsc/__init__.py 2010-06-06 15:52:13 UTC (rev 436) @@ -1 +0,0 @@ - This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 15:50:04
|
Revision: 435 http://pyscard.svn.sourceforge.net/pyscard/?rev=435&view=rev Author: ludov Date: 2010-06-06 15:49:58 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/Examples/wx/readerviewer/readerviewer.py Modified: trunk/pyscard/src/smartcard/Examples/wx/readerviewer/readerviewer.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/wx/readerviewer/readerviewer.py 2010-06-06 15:48:18 UTC (rev 434) +++ trunk/pyscard/src/smartcard/Examples/wx/readerviewer/readerviewer.py 2010-06-06 15:49:58 UTC (rev 435) @@ -26,15 +26,16 @@ import os.path from smartcard.wx.SimpleSCardApp import * -def main( argv ): + +def main(argv): app = SimpleSCardApp( appname='A simple reader monitoring tool', apppanel=None, appstyle=TR_READER, - appicon=os.path.join( os.path.dirname( __file__ ), 'images', 'readerviewer.ico' ), - size=(800, 600) ) + appicon=os.path.join(os.path.dirname(__file__), 'images', 'readerviewer.ico'), + size=(800, 600)) app.MainLoop() if __name__ == "__main__": import sys - main( sys.argv ) + main(sys.argv) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 15:48:24
|
Revision: 434 http://pyscard.svn.sourceforge.net/pyscard/?rev=434&view=rev Author: ludov Date: 2010-06-06 15:48:18 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/Examples/wx/pcscdiag/pcscdiag.py Modified: trunk/pyscard/src/smartcard/Examples/wx/pcscdiag/pcscdiag.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/wx/pcscdiag/pcscdiag.py 2010-06-06 15:46:45 UTC (rev 433) +++ trunk/pyscard/src/smartcard/Examples/wx/pcscdiag/pcscdiag.py 2010-06-06 15:48:18 UTC (rev 434) @@ -43,51 +43,50 @@ sys.exit() -def getATR( reader ): +def getATR(reader): """Return the ATR of the card inserted into the reader.""" - connection=reader.createConnection() - atr="" + connection = reader.createConnection() + atr = "" try: connection.connect() - atr=smartcard.util.toHexString( connection.getATR() ) + atr = smartcard.util.toHexString(connection.getATR()) connection.disconnect() except smartcard.Exceptions.NoCardException: - atr="no card inserted" + atr = "no card inserted" return atr -class pcscdiag( wx.Frame ): +class pcscdiag(wx.Frame): + def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, size=(600, 400)) w, h = self.GetClientSizeTuple() - self.tree = wx.TreeCtrl( self, wx.NewId(), wx.DefaultPosition, (w, h), wx.TR_HAS_BUTTONS | wx.TR_EDIT_LABELS ) + self.tree = wx.TreeCtrl(self, wx.NewId(), wx.DefaultPosition, (w, h), wx.TR_HAS_BUTTONS | wx.TR_EDIT_LABELS) self.InitTree() self.OnExpandAll() - - def InitTree( self ): + def InitTree(self): self.tree.AddRoot("Readers and ReaderGroups") - readerNode = self.tree.AppendItem( self.tree.GetRootItem(), "Readers" ) + readerNode = self.tree.AppendItem(self.tree.GetRootItem(), "Readers") for reader in smartcard.System.readers(): - childReader = self.tree.AppendItem( readerNode, `reader` ) - childCard = self.tree.AppendItem( childReader, getATR( reader ) ) + childReader = self.tree.AppendItem(readerNode, `reader`) + childCard = self.tree.AppendItem(childReader, getATR(reader)) - readerGroupNode = self.tree.AppendItem( self.tree.GetRootItem(), "Readers Groups") + readerGroupNode = self.tree.AppendItem(self.tree.GetRootItem(), "Readers Groups") for readergroup in smartcard.System.readergroups(): - childReaderGroup = self.tree.AppendItem( readerGroupNode, readergroup ) - readers=smartcard.System.readers( readergroup ) + childReaderGroup = self.tree.AppendItem(readerGroupNode, readergroup) + readers = smartcard.System.readers(readergroup) for reader in readers: - child = self.tree.AppendItem( childReaderGroup, `reader` ) + child = self.tree.AppendItem(childReaderGroup, `reader`) - - def OnExpandAll(self ): + def OnExpandAll(self): """ expand all nodes """ root = self.tree.GetRootItem() fn = self.tree.Expand self.traverse(root, fn) - self.tree.Expand( root ) + self.tree.Expand(root) def traverse(self, traverseroot, function, cookie=0): """ recursivly walk tree control """ @@ -104,6 +103,6 @@ if __name__ == '__main__': app = wx.PySimpleApp() - frame = pcscdiag( None, "Smartcard readers and reader groups" ) + frame = pcscdiag(None, "Smartcard readers and reader groups") frame.Show() app.MainLoop() This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 15:46:52
|
Revision: 433 http://pyscard.svn.sourceforge.net/pyscard/?rev=433&view=rev Author: ludov Date: 2010-06-06 15:46:45 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/Examples/wx/cardmonitor/cardmonitor.py Modified: trunk/pyscard/src/smartcard/Examples/wx/cardmonitor/cardmonitor.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/wx/cardmonitor/cardmonitor.py 2010-06-06 15:44:49 UTC (rev 432) +++ trunk/pyscard/src/smartcard/Examples/wx/cardmonitor/cardmonitor.py 2010-06-06 15:46:45 UTC (rev 433) @@ -30,70 +30,72 @@ ID_TEXT = 10000 -class SamplePanel( wx.Panel, SimpleSCardAppEventObserver ): + +class SamplePanel(wx.Panel, SimpleSCardAppEventObserver): '''A simple panel that displays activated cards and readers. The panel implements the SimpleSCardAppEventObserver, and has a chance to react on reader and card activation/deactivation.''' - def __init__( self, parent ): - wx.Panel.__init__( self, parent, -1 ) - sizer = wx.FlexGridSizer( 0, 3, 0, 0 ) - sizer.AddGrowableCol( 1 ) - sizer.AddGrowableRow( 1 ) + def __init__(self, parent): + wx.Panel.__init__(self, parent, -1) - sizer.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) - sizer.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) - sizer.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) - sizer.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) + sizer = wx.FlexGridSizer(0, 3, 0, 0) + sizer.AddGrowableCol(1) + sizer.AddGrowableRow(1) - self.feedbacktext = wx.StaticText( self, ID_TEXT, "", wx.DefaultPosition, wx.DefaultSize, 0 ) - sizer.Add( self.feedbacktext, 0, wx.ALIGN_LEFT|wx.ALL, 5 ) + sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) + sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) + sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) + sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) - sizer.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) - sizer.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) - sizer.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) - sizer.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) + self.feedbacktext = wx.StaticText(self, ID_TEXT, "", wx.DefaultPosition, wx.DefaultSize, 0) + sizer.Add(self.feedbacktext, 0, wx.ALIGN_LEFT | wx.ALL, 5) + sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) + sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) + sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) + sizer.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) + self.SetSizer(sizer) self.SetAutoLayout(True) # callbacks from SimpleSCardAppEventObserver interface - def OnActivateCard( self, card ): + def OnActivateCard(self, card): """Called when a card is activated by double-clicking on the card or reader tree control or toolbar. In this sample, we just connect to the card on the first activation.""" - SimpleSCardAppEventObserver.OnActivateCard( self, card ) - self.feedbacktext.SetLabel( 'Activated card: ' + `card` ) + SimpleSCardAppEventObserver.OnActivateCard(self, card) + self.feedbacktext.SetLabel('Activated card: ' + `card`) - def OnActivateReader( self, reader ): + def OnActivateReader(self, reader): """Called when a reader is activated by double-clicking on the reader tree control or toolbar.""" - SimpleSCardAppEventObserver.OnActivateReader( self, reader ) - self.feedbacktext.SetLabel( 'Activated reader: ' + `reader` ) + SimpleSCardAppEventObserver.OnActivateReader(self, reader) + self.feedbacktext.SetLabel('Activated reader: ' + `reader`) - def OnDeactivateCard( self, card ): + def OnDeactivateCard(self, card): """Called when a card is deactivated in the reader tree control or toolbar.""" - SimpleSCardAppEventObserver.OnActivateCard( self, card ) - self.feedbacktext.SetLabel( 'Deactivated card: ' + `card` ) + SimpleSCardAppEventObserver.OnActivateCard(self, card) + self.feedbacktext.SetLabel('Deactivated card: ' + `card`) - def OnSelectCard( self, card ): + def OnSelectCard(self, card): """Called when a card is selected by clicking on the card or reader tree control or toolbar.""" - SimpleSCardAppEventObserver.OnSelectCard( self, card ) - self.feedbacktext.SetLabel( 'Selected card: ' + `card` ) + SimpleSCardAppEventObserver.OnSelectCard(self, card) + self.feedbacktext.SetLabel('Selected card: ' + `card`) - def OnSelectReader( self, reader ): + def OnSelectReader(self, reader): """Called when a reader is selected by clicking on the reader tree control or toolbar.""" - SimpleSCardAppEventObserver.OnSelectReader( self, reader ) - self.feedbacktext.SetLabel( 'Selected reader: ' + `reader` ) + SimpleSCardAppEventObserver.OnSelectReader(self, reader) + self.feedbacktext.SetLabel('Selected reader: ' + `reader`) -def main( argv ): +def main(argv): app = SimpleSCardApp( appname='A simple card monitoring tool', apppanel=SamplePanel, appstyle=TR_SMARTCARD | TR_READER, - appicon=os.path.join( os.path.dirname( __file__ ), 'images', 'mysmartcard.ico' ), - size=(800, 600) ) + appicon=os.path.join(os.path.dirname(__file__), 'images', 'mysmartcard.ico'), + size=(800, 600)) app.MainLoop() if __name__ == "__main__": import sys - main( sys.argv ) + main(sys.argv) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 15:44:55
|
Revision: 432 http://pyscard.svn.sourceforge.net/pyscard/?rev=432&view=rev Author: ludov Date: 2010-06-06 15:44:49 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/Examples/wx/apdumanager/SampleAPDUManagerPanel.py trunk/pyscard/src/smartcard/Examples/wx/apdumanager/apdumanager.py Modified: trunk/pyscard/src/smartcard/Examples/wx/apdumanager/SampleAPDUManagerPanel.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/wx/apdumanager/SampleAPDUManagerPanel.py 2010-06-06 15:39:16 UTC (rev 431) +++ trunk/pyscard/src/smartcard/Examples/wx/apdumanager/SampleAPDUManagerPanel.py 2010-06-06 15:44:49 UTC (rev 432) @@ -40,131 +40,132 @@ ID_TEXT_SW2, ID_TEXTCTRL_SW2, ID_CARDSTATE, -ID_TRANSMIT -] = map( lambda x: wx.NewId(), range(11) ) +ID_TRANSMIT] = map(lambda x: wx.NewId(), range(11)) -class SampleAPDUManagerPanel( wx.Panel, SimpleSCardAppEventObserver ): + +class SampleAPDUManagerPanel(wx.Panel, SimpleSCardAppEventObserver): '''A simple panel that displays activated cards and readers and can send APDU to a connected card.''' - def __init__( self, parent ): - wx.Panel.__init__( self, parent, -1 ) - SimpleSCardAppEventObserver.__init__( self ) + + def __init__(self, parent): + wx.Panel.__init__(self, parent, -1) + SimpleSCardAppEventObserver.__init__(self) self.layoutControls() - self.Bind( wx.EVT_BUTTON, self.OnTransmit, self.transmitbutton ) + self.Bind(wx.EVT_BUTTON, self.OnTransmit, self.transmitbutton) # callbacks from SimpleSCardAppEventObserver interface - def OnActivateCard( self, card ): + def OnActivateCard(self, card): """Called when a card is activated by double-clicking on the card or reader tree control or toolbar. In this sample, we just connect to the card on the first activation.""" - SimpleSCardAppEventObserver.OnActivateCard( self, card ) - self.feedbacktext.SetLabel( 'Activated card: ' + `card` ) + SimpleSCardAppEventObserver.OnActivateCard(self, card) + self.feedbacktext.SetLabel('Activated card: ' + `card`) self.transmitbutton.Enable() - def OnActivateReader( self, reader ): + def OnActivateReader(self, reader): """Called when a reader is activated by double-clicking on the reader tree control or toolbar.""" - SimpleSCardAppEventObserver.OnActivateReader( self, reader ) - self.feedbacktext.SetLabel( 'Activated reader: ' + `reader` ) + SimpleSCardAppEventObserver.OnActivateReader(self, reader) + self.feedbacktext.SetLabel('Activated reader: ' + `reader`) self.transmitbutton.Disable() - def OnDeactivateCard( self, card ): + def OnDeactivateCard(self, card): """Called when a card is deactivated in the reader tree control or toolbar.""" - SimpleSCardAppEventObserver.OnActivateCard( self, card ) - self.feedbacktext.SetLabel( 'Deactivated card: ' + `card` ) + SimpleSCardAppEventObserver.OnActivateCard(self, card) + self.feedbacktext.SetLabel('Deactivated card: ' + `card`) self.transmitbutton.Disable() - def OnDeselectCard( self, card ): + def OnDeselectCard(self, card): """Called when a card is selected by clicking on the card or reader tree control or toolbar.""" - SimpleSCardAppEventObserver.OnSelectCard( self, card ) - self.feedbacktext.SetLabel( 'Deselected card: ' + `card` ) + SimpleSCardAppEventObserver.OnSelectCard(self, card) + self.feedbacktext.SetLabel('Deselected card: ' + `card`) self.transmitbutton.Disable() - def OnSelectCard( self, card ): + def OnSelectCard(self, card): """Called when a card is selected by clicking on the card or reader tree control or toolbar.""" - SimpleSCardAppEventObserver.OnSelectCard( self, card ) - self.feedbacktext.SetLabel( 'Selected card: ' + `card` ) - if hasattr( self.selectedcard, 'connection' ): + SimpleSCardAppEventObserver.OnSelectCard(self, card) + self.feedbacktext.SetLabel('Selected card: ' + `card`) + if hasattr(self.selectedcard, 'connection'): self.transmitbutton.Enable() - def OnSelectReader( self, reader ): + def OnSelectReader(self, reader): """Called when a reader is selected by clicking on the reader tree control or toolbar.""" - SimpleSCardAppEventObserver.OnSelectReader( self, reader ) - self.feedbacktext.SetLabel( 'Selected reader: ' + `reader` ) + SimpleSCardAppEventObserver.OnSelectReader(self, reader) + self.feedbacktext.SetLabel('Selected reader: ' + `reader`) self.transmitbutton.Disable() # callbacks - def OnTransmit( self, event ): - if hasattr( self.selectedcard, 'connection' ): + def OnTransmit(self, event): + if hasattr(self.selectedcard, 'connection'): apdu = self.commandtextctrl.GetValue() - if type(u'')==type( apdu ): - apdu=apdu.encode('utf8') - data, sw1, sw2 = self.selectedcard.connection.transmit( toBytes( apdu ) ) - self.SW1textctrl.SetValue( "%x" % sw1 ) - self.SW2textctrl.SetValue( "%x" % sw2 ) - self.responsetextctrl.SetValue( toHexString( data + [sw1, sw2] ) ) + if type(u'') == type(apdu): + apdu = apdu.encode('utf8') + data, sw1, sw2 = self.selectedcard.connection.transmit(toBytes(apdu)) + self.SW1textctrl.SetValue("%x" % sw1) + self.SW2textctrl.SetValue("%x" % sw2) + self.responsetextctrl.SetValue(toHexString(data + [sw1, sw2])) event.Skip() - def layoutControls( self ): + def layoutControls(self): # create controls - statictextCommand = wx.StaticText( self, ID_TEXT_COMMAND, "Command", wx.DefaultPosition, wx.DefaultSize, 0 ) - self.commandtextctrl = wx.TextCtrl( self, ID_TEXTCTRL_COMMAND, "", + statictextCommand = wx.StaticText(self, ID_TEXT_COMMAND, "Command", wx.DefaultPosition, wx.DefaultSize, 0) + self.commandtextctrl = wx.TextCtrl(self, ID_TEXTCTRL_COMMAND, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE, - validator=APDUHexValidator() ) - statictextResponse = wx.StaticText( self, ID_TEXT_RESPONSE, "Response", wx.DefaultPosition, wx.DefaultSize, 0 ) - self.responsetextctrl = wx.TextCtrl( self, ID_TEXTCTRL_RESPONSE, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE | wx.TE_READONLY ) - statictextStatusWords = wx.StaticText( self, ID_TEXT_SW, "Status Words", wx.DefaultPosition, wx.DefaultSize, 0 ) - statictextSW1 = wx.StaticText( self, ID_TEXT_SW1, "SW1", wx.DefaultPosition, wx.DefaultSize, 0 ) - self.SW1textctrl = wx.TextCtrl( self, ID_TEXTCTRL_SW1, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_READONLY ) - statictextSW2 = wx.StaticText( self, ID_TEXT_SW2, "SW2", wx.DefaultPosition, wx.DefaultSize, 0 ) - self.SW2textctrl = wx.TextCtrl( self, ID_TEXTCTRL_SW2, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_READONLY ) - self.feedbacktext = wx.StaticText( self, ID_CARDSTATE, "", wx.DefaultPosition, wx.DefaultSize, 0 ) + validator=APDUHexValidator()) + statictextResponse = wx.StaticText(self, ID_TEXT_RESPONSE, "Response", wx.DefaultPosition, wx.DefaultSize, 0) + self.responsetextctrl = wx.TextCtrl(self, ID_TEXTCTRL_RESPONSE, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE | wx.TE_READONLY) + statictextStatusWords = wx.StaticText(self, ID_TEXT_SW, "Status Words", wx.DefaultPosition, wx.DefaultSize, 0) + statictextSW1 = wx.StaticText(self, ID_TEXT_SW1, "SW1", wx.DefaultPosition, wx.DefaultSize, 0) + self.SW1textctrl = wx.TextCtrl(self, ID_TEXTCTRL_SW1, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_READONLY) + statictextSW2 = wx.StaticText(self, ID_TEXT_SW2, "SW2", wx.DefaultPosition, wx.DefaultSize, 0) + self.SW2textctrl = wx.TextCtrl(self, ID_TEXTCTRL_SW2, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_READONLY) + self.feedbacktext = wx.StaticText(self, ID_CARDSTATE, "", wx.DefaultPosition, wx.DefaultSize, 0) # layout controls - boxsizerCommand = wx.BoxSizer( wx.HORIZONTAL ) - boxsizerCommand.Add( statictextCommand, 1, wx.ALIGN_CENTER | wx.ALL, 5 ) - boxsizerCommand.Add( self.commandtextctrl, 5, wx.EXPAND | wx.ALL, 5 ) + boxsizerCommand = wx.BoxSizer(wx.HORIZONTAL) + boxsizerCommand.Add(statictextCommand, 1, wx.ALIGN_CENTER | wx.ALL, 5) + boxsizerCommand.Add(self.commandtextctrl, 5, wx.EXPAND | wx.ALL, 5) - boxsizerResponse = wx.BoxSizer( wx.HORIZONTAL ) - boxsizerResponse.Add( statictextResponse, 1, wx.ALIGN_CENTER | wx.ALL, 5 ) - boxsizerResponse.Add( self.responsetextctrl, 5, wx.EXPAND | wx.ALL, 5 ) + boxsizerResponse = wx.BoxSizer(wx.HORIZONTAL) + boxsizerResponse.Add(statictextResponse, 1, wx.ALIGN_CENTER | wx.ALL, 5) + boxsizerResponse.Add(self.responsetextctrl, 5, wx.EXPAND | wx.ALL, 5) - boxsizerSW = wx.BoxSizer( wx.HORIZONTAL ) - boxsizerSW.Add( statictextSW1, 0, wx.ALIGN_CENTER | wx.ALL, 5 ) - boxsizerSW.Add( self.SW1textctrl, 0, wx.EXPAND | wx.ALL, 5 ) - boxsizerSW.Add( statictextSW2, 0, wx.ALIGN_CENTER|wx.ALL, 5 ) - boxsizerSW.Add( self.SW2textctrl, 0, wx.EXPAND|wx.ALL, 5 ) + boxsizerSW = wx.BoxSizer(wx.HORIZONTAL) + boxsizerSW.Add(statictextSW1, 0, wx.ALIGN_CENTER | wx.ALL, 5) + boxsizerSW.Add(self.SW1textctrl, 0, wx.EXPAND | wx.ALL, 5) + boxsizerSW.Add(statictextSW2, 0, wx.ALIGN_CENTER | wx.ALL, 5) + boxsizerSW.Add(self.SW2textctrl, 0, wx.EXPAND | wx.ALL, 5) - item11 = wx.BoxSizer( wx.HORIZONTAL ) - item11.Add( statictextStatusWords, 0, wx.ALIGN_CENTER | wx.ALL, 5 ) - item11.Add( boxsizerSW, 0, wx.EXPAND | wx.ALL, 5 ) + item11 = wx.BoxSizer(wx.HORIZONTAL) + item11.Add(statictextStatusWords, 0, wx.ALIGN_CENTER | wx.ALL, 5) + item11.Add(boxsizerSW, 0, wx.EXPAND | wx.ALL, 5) - boxsizerResponseAndSW = wx.BoxSizer( wx.VERTICAL ) - boxsizerResponseAndSW.Add( boxsizerResponse, 0, wx.EXPAND|wx.ALL, 5 ) - boxsizerResponseAndSW.Add( item11, 0, wx.EXPAND|wx.ALL, 5 ) + boxsizerResponseAndSW = wx.BoxSizer(wx.VERTICAL) + boxsizerResponseAndSW.Add(boxsizerResponse, 0, wx.EXPAND | wx.ALL, 5) + boxsizerResponseAndSW.Add(item11, 0, wx.EXPAND | wx.ALL, 5) - staticboxAPDU = wx.StaticBox( self, -1, "APDU" ) - boxsizerAPDU = wx.StaticBoxSizer( staticboxAPDU, wx.VERTICAL ) - boxsizerAPDU.Add( boxsizerCommand, 1, wx.EXPAND | wx.ALL, 5 ) - boxsizerAPDU.Add( boxsizerResponseAndSW, 4, wx.EXPAND | wx.ALL, 5 ) + staticboxAPDU = wx.StaticBox(self, -1, "APDU") + boxsizerAPDU = wx.StaticBoxSizer(staticboxAPDU, wx.VERTICAL) + boxsizerAPDU.Add(boxsizerCommand, 1, wx.EXPAND | wx.ALL, 5) + boxsizerAPDU.Add(boxsizerResponseAndSW, 4, wx.EXPAND | wx.ALL, 5) - staticboxEvents = wx.StaticBox( self, -1, "Card/Reader Events" ) - boxsizerEvents = wx.StaticBoxSizer( staticboxEvents, wx.HORIZONTAL ) - boxsizerEvents.Add( self.feedbacktext, 0, wx.ALIGN_CENTER | wx.ALL, 5 ) + staticboxEvents = wx.StaticBox(self, -1, "Card/Reader Events") + boxsizerEvents = wx.StaticBoxSizer(staticboxEvents, wx.HORIZONTAL) + boxsizerEvents.Add(self.feedbacktext, 0, wx.ALIGN_CENTER | wx.ALL, 5) - sizerboxTransmitButton = wx.BoxSizer( wx.HORIZONTAL ) - sizerboxTransmitButton.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) - self.transmitbutton = wx.Button( self, ID_TRANSMIT, "Transmit", wx.DefaultPosition, wx.DefaultSize, 0 ) + sizerboxTransmitButton = wx.BoxSizer(wx.HORIZONTAL) + sizerboxTransmitButton.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) + self.transmitbutton = wx.Button(self, ID_TRANSMIT, "Transmit", wx.DefaultPosition, wx.DefaultSize, 0) self.transmitbutton.Disable() - sizerboxTransmitButton.Add( self.transmitbutton, 0, wx.ALIGN_CENTER|wx.ALL, 5 ) - sizerboxTransmitButton.Add( [ 20, 20 ] , 0, wx.ALIGN_CENTER|wx.ALL, 5 ) + sizerboxTransmitButton.Add(self.transmitbutton, 0, wx.ALIGN_CENTER | wx.ALL, 5) + sizerboxTransmitButton.Add([20, 20], 0, wx.ALIGN_CENTER | wx.ALL, 5) - sizerPanel = wx.BoxSizer( wx.VERTICAL ) - sizerPanel.Add( boxsizerAPDU, 3, wx.EXPAND | wx.ALL, 5 ) - sizerPanel.Add( boxsizerEvents, 1, wx.EXPAND | wx.ALL, 5 ) - sizerPanel.Add( sizerboxTransmitButton, 1, wx.EXPAND | wx.ALL, 5 ) + sizerPanel = wx.BoxSizer(wx.VERTICAL) + sizerPanel.Add(boxsizerAPDU, 3, wx.EXPAND | wx.ALL, 5) + sizerPanel.Add(boxsizerEvents, 1, wx.EXPAND | wx.ALL, 5) + sizerPanel.Add(sizerboxTransmitButton, 1, wx.EXPAND | wx.ALL, 5) - self.SetSizer( sizerPanel ) + self.SetSizer(sizerPanel) self.SetAutoLayout(True) sizerPanel.Fit(self) Modified: trunk/pyscard/src/smartcard/Examples/wx/apdumanager/apdumanager.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/wx/apdumanager/apdumanager.py 2010-06-06 15:39:16 UTC (rev 431) +++ trunk/pyscard/src/smartcard/Examples/wx/apdumanager/apdumanager.py 2010-06-06 15:44:49 UTC (rev 432) @@ -29,15 +29,16 @@ from SampleAPDUManagerPanel import SampleAPDUManagerPanel -def main( argv ): + +def main(argv): app = SimpleSCardApp( appname='A tool to send apdu to a card', apppanel=SampleAPDUManagerPanel, appstyle=TR_SMARTCARD | TR_READER | PANEL_APDUTRACER, - appicon=os.path.join( os.path.dirname( __file__ ), 'images', 'mysmartcard.ico' ), - size=(800, 600) ) + appicon=os.path.join(os.path.dirname(__file__), 'images', 'mysmartcard.ico'), + size=(800, 600)) app.MainLoop() if __name__ == "__main__": import sys - main( sys.argv ) + main(sys.argv) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <lu...@us...> - 2010-06-06 15:39:23
|
Revision: 431 http://pyscard.svn.sourceforge.net/pyscard/?rev=431&view=rev Author: ludov Date: 2010-06-06 15:39:16 +0000 (Sun, 06 Jun 2010) Log Message: ----------- make pep8 happy Modified Paths: -------------- trunk/pyscard/src/smartcard/Examples/framework/sample_ATR.py trunk/pyscard/src/smartcard/Examples/framework/sample_CardConnectionDecorator.py trunk/pyscard/src/smartcard/Examples/framework/sample_ConsoleConnectionTracer.py trunk/pyscard/src/smartcard/Examples/framework/sample_CustomCardType.py trunk/pyscard/src/smartcard/Examples/framework/sample_CustomErrorChecker.py trunk/pyscard/src/smartcard/Examples/framework/sample_ErrorChecking.py trunk/pyscard/src/smartcard/Examples/framework/sample_ExclusiveCardConnection.py trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorCards.py trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorCardsAndTransmit.py trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorReaders.py trunk/pyscard/src/smartcard/Examples/framework/sample_TransmitCardObserver.py trunk/pyscard/src/smartcard/Examples/framework/sample_apduTracerInterpreter.py trunk/pyscard/src/smartcard/Examples/framework/sample_toHexString.py Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_ATR.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_ATR.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_ATR.py 2010-06-06 15:39:16 UTC (rev 431) @@ -28,10 +28,10 @@ atr = ATR([0x3B, 0x9E, 0x95, 0x80, 0x1F, 0xC3, 0x80, 0x31, 0xA0, 0x73, 0xBE, 0x21, 0x13, 0x67, 0x29, 0x02, 0x01, 0x01, 0x81, - 0xCD, 0xB9] ) + 0xCD, 0xB9]) print atr -print 'historical bytes: ', toHexString( atr.getHistoricalBytes() ) +print 'historical bytes: ', toHexString(atr.getHistoricalBytes()) print 'checksum: ', "0x%X" % atr.getChecksum() print 'checksum OK: ', atr.checksumOK print 'T0 supported: ', atr.isT0Supported() Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_CardConnectionDecorator.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_CardConnectionDecorator.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_CardConnectionDecorator.py 2010-06-06 15:39:16 UTC (rev 431) @@ -35,74 +35,78 @@ # shortly how several decorators can be added to the # card connection -class SecureChannelConnection( CardConnectionDecorator ): + +class SecureChannelConnection(CardConnectionDecorator): '''This decorator is a mockup of secure channel connection. It merely pretends to cypher/uncypher upon apdu transmission.''' - def __init__( self, cardconnection ): - CardConnectionDecorator.__init__( self, cardconnection ) - def cypher( self, bytes ): + def __init__(self, cardconnection): + CardConnectionDecorator.__init__(self, cardconnection) + + def cypher(self, bytes): '''Cypher mock-up; you would include the secure channel logics here.''' - print 'cyphering', toHexString( bytes ) + print 'cyphering', toHexString(bytes) return bytes - def uncypher( self, data ): + def uncypher(self, data): '''Uncypher mock-up; you would include the secure channel logics here.''' - print 'uncyphering', toHexString( data ) + print 'uncyphering', toHexString(data) return data - def transmit( self, bytes, protocol=None ): + def transmit(self, bytes, protocol=None): """Cypher/uncypher APDUs before transmission""" - cypheredbytes = self.cypher( bytes ) - data, sw1, sw2 = CardConnectionDecorator.transmit( self, cypheredbytes, protocol ) - if []!=data: - data = self.uncypher( data ) + cypheredbytes = self.cypher(bytes) + data, sw1, sw2 = CardConnectionDecorator.transmit(self, cypheredbytes, protocol) + if [] != data: + data = self.uncypher(data) return data, sw1, sw2 -class FakeATRConnection( CardConnectionDecorator ): + +class FakeATRConnection(CardConnectionDecorator): '''This decorator changes the fist byte of the ATR. This is just an example to show that decorators can be nested.''' - def __init__( self, cardconnection ): - CardConnectionDecorator.__init__( self, cardconnection ) - def getATR( self ): + def __init__(self, cardconnection): + CardConnectionDecorator.__init__(self, cardconnection) + + def getATR(self): """Replace first BYTE of ATR by 3F""" - atr = CardConnectionDecorator.getATR( self ) - return [ 0x3f ] + atr[1:] + atr = CardConnectionDecorator.getATR(self) + return [0x3f] + atr[1:] # define the apdus used in this script -GET_RESPONSE = [0XA0, 0XC0, 00, 00 ] +GET_RESPONSE = [0XA0, 0XC0, 00, 00] SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] # request any card type cardtype = AnyCardType() -cardrequest = CardRequest( timeout=1.5, cardType=cardtype ) +cardrequest = CardRequest(timeout=1.5, cardType=cardtype) cardservice = cardrequest.waitforcard() # attach the console tracer -observer=ConsoleCardConnectionObserver() -cardservice.connection.addObserver( observer ) +observer = ConsoleCardConnectionObserver() +cardservice.connection.addObserver(observer) # attach our decorator -cardservice.connection = FakeATRConnection( SecureChannelConnection( cardservice.connection ) ) +cardservice.connection = FakeATRConnection(SecureChannelConnection(cardservice.connection)) # connect to the card and perform a few transmits cardservice.connection.connect() -print 'ATR', toHexString( cardservice.connection.getATR() ) +print 'ATR', toHexString(cardservice.connection.getATR()) -apdu = SELECT+DF_TELECOM -response, sw1, sw2 = cardservice.connection.transmit( apdu ) +apdu = SELECT + DF_TELECOM +response, sw1, sw2 = cardservice.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_RESPONSE + [sw2] - response, sw1, sw2 = cardservice.connection.transmit( apdu ) + response, sw1, sw2 = cardservice.connection.transmit(apdu) import sys -if 'win32'==sys.platform: +if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_ConsoleConnectionTracer.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_ConsoleConnectionTracer.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_ConsoleConnectionTracer.py 2010-06-06 15:39:16 UTC (rev 431) @@ -28,34 +28,34 @@ from smartcard.CardConnectionObserver import ConsoleCardConnectionObserver # define the apdus used in this script -GET_RESPONSE = [0XA0, 0XC0, 00, 00 ] +GET_RESPONSE = [0XA0, 0XC0, 00, 00] SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] # request any card type cardtype = AnyCardType() -cardrequest = CardRequest( timeout=1.5, cardType=cardtype ) +cardrequest = CardRequest(timeout=1.5, cardType=cardtype) cardservice = cardrequest.waitforcard() # attach the console tracer -observer=ConsoleCardConnectionObserver() -cardservice.connection.addObserver( observer ) +observer = ConsoleCardConnectionObserver() +cardservice.connection.addObserver(observer) # connect to the card and perform a few transmits cardservice.connection.connect() -apdu = SELECT+DF_TELECOM -response, sw1, sw2 = cardservice.connection.transmit( apdu ) +apdu = SELECT + DF_TELECOM +response, sw1, sw2 = cardservice.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_RESPONSE + [sw2] - response, sw1, sw2 = cardservice.connection.transmit( apdu ) + response, sw1, sw2 = cardservice.connection.transmit(apdu) import sys -if 'win32'==sys.platform: +if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_CustomCardType.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_CustomCardType.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_CustomCardType.py 2010-06-06 15:39:16 UTC (rev 431) @@ -27,26 +27,28 @@ from smartcard.CardRequest import CardRequest from smartcard.util import toHexString + +class DCCardType(CardType): # define our custom CardType # this card type defines direct convention card (first atr byte equal to 0x3b) -class DCCardType(CardType): - def matches( self, atr, reader=None ): - return atr[0]==0x3B + def matches(self, atr, reader=None): + return atr[0] == 0x3B + # request a direct convention card cardtype = DCCardType() -cardrequest = CardRequest( timeout=1, cardType=cardtype ) +cardrequest = CardRequest(timeout=1, cardType=cardtype) cardservice = cardrequest.waitforcard() # connect and print atr and reader cardservice.connection.connect() -print toHexString( cardservice.connection.getATR() ) +print toHexString(cardservice.connection.getATR()) print cardservice.connection.getReader() import sys -if 'win32'==sys.platform: +if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_CustomErrorChecker.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_CustomErrorChecker.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_CustomErrorChecker.py 2010-06-06 15:39:16 UTC (rev 431) @@ -32,16 +32,16 @@ from smartcard.sw.SWExceptions import SWException +class MyErrorChecker(ErrorChecker): + """Our custom error checker that will except if 0x61<sw1<0x70.""" -class MyErrorChecker( ErrorChecker ): - """Our custom error checker that will except if 0x61<sw1<0x70.""" - def __call__( self, data, sw1, sw2 ): + def __call__(self, data, sw1, sw2): print sw1, sw2 - if 0x61<sw1 and 0x70>sw1: - raise SWException( data, sw1, sw2 ) + if 0x61 < sw1 and 0x70 > sw1: + raise SWException(data, sw1, sw2) # define the apdus used in this script -GET_RESPONSE = [0XA0, 0XC0, 00, 00 ] +GET_RESPONSE = [0XA0, 0XC0, 00, 00] SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] @@ -52,17 +52,17 @@ # request any card cardtype = AnyCardType() - cardrequest = CardRequest( timeout=10, cardType=cardtype ) + cardrequest = CardRequest(timeout=10, cardType=cardtype) cardservice = cardrequest.waitforcard() # our error checking chain - errorchain=[] - errorchain=[ ErrorCheckingChain( [], MyErrorChecker() ) ] - cardservice.connection.setErrorCheckingChain( errorchain ) + errorchain = [] + errorchain = [ErrorCheckingChain([], MyErrorChecker())] + cardservice.connection.setErrorCheckingChain(errorchain) # attach the console tracer - observer=ConsoleCardConnectionObserver() - cardservice.connection.addObserver( observer ) + observer = ConsoleCardConnectionObserver() + cardservice.connection.addObserver(observer) # send a few apdus; exceptions will occur upon errors cardservice.connection.connect() @@ -70,18 +70,18 @@ try: SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] - apdu = SELECT+DF_TELECOM - response, sw1, sw2 = cardservice.connection.transmit( apdu ) + apdu = SELECT + DF_TELECOM + response, sw1, sw2 = cardservice.connection.transmit(apdu) if sw1 == 0x9F: - GET_RESPONSE = [0XA0, 0XC0, 00, 00 ] + GET_RESPONSE = [0XA0, 0XC0, 00, 00] apdu = GET_RESPONSE + [sw2] - response, sw1, sw2 = cardservice.connection.transmit( apdu ) + response, sw1, sw2 = cardservice.connection.transmit(apdu) except SWException, e: - print e, "%x %x" % (e.sw1, e.sw2 ) + print e, "%x %x" % (e.sw1, e.sw2) cardservice.connection.disconnect() import sys - if 'win32'==sys.platform: + if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_ErrorChecking.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_ErrorChecking.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_ErrorChecking.py 2010-06-06 15:39:16 UTC (rev 431) @@ -36,7 +36,7 @@ # define the apdus used in this script -GET_RESPONSE = [0XA0, 0XC0, 00, 00 ] +GET_RESPONSE = [0XA0, 0XC0, 00, 00] SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] @@ -48,34 +48,34 @@ # request any card type cardtype = AnyCardType() - cardrequest = CardRequest( timeout=10, cardType=cardtype ) + cardrequest = CardRequest(timeout=10, cardType=cardtype) cardservice = cardrequest.waitforcard() # use ISO7816-4 and ISO7816-8 error checking strategy # first check iso7816_8 errors, then iso7816_4 errors - errorchain=[] - errorchain=[ ErrorCheckingChain( errorchain, ISO7816_9ErrorChecker() ) ] - errorchain=[ ErrorCheckingChain( errorchain, ISO7816_8ErrorChecker() ) ] - errorchain=[ ErrorCheckingChain( errorchain, ISO7816_4ErrorChecker() ) ] - cardservice.connection.setErrorCheckingChain( errorchain ) + errorchain = [] + errorchain = [ErrorCheckingChain(errorchain, ISO7816_9ErrorChecker())] + errorchain = [ErrorCheckingChain(errorchain, ISO7816_8ErrorChecker())] + errorchain = [ErrorCheckingChain(errorchain, ISO7816_4ErrorChecker())] + cardservice.connection.setErrorCheckingChain(errorchain) # filter Warning Processing Exceptions (sw1 = 0x62 or 0x63) - cardservice.connection.addSWExceptionToFilter( WarningProcessingException ) + cardservice.connection.addSWExceptionToFilter(WarningProcessingException) # attach the console tracer - observer=ConsoleCardConnectionObserver() - cardservice.connection.addObserver( observer ) + observer = ConsoleCardConnectionObserver() + cardservice.connection.addObserver(observer) # connect to the card and perform a few transmits cardservice.connection.connect() try: - apdu = SELECT+DF_TELECOM - response, sw1, sw2 = cardservice.connection.transmit( apdu ) + apdu = SELECT + DF_TELECOM + response, sw1, sw2 = cardservice.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_RESPONSE + [sw2] - response, sw1, sw2 = cardservice.connection.transmit( apdu ) + response, sw1, sw2 = cardservice.connection.transmit(apdu) except SWException, e: print str(e) @@ -83,6 +83,6 @@ cardservice.connection.disconnect() import sys - if 'win32'==sys.platform: + if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_ExclusiveCardConnection.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_ExclusiveCardConnection.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_ExclusiveCardConnection.py 2010-06-06 15:39:16 UTC (rev 431) @@ -34,40 +34,40 @@ # define the apdus used in this script -GET_RESPONSE = [0XA0, 0XC0, 00, 00 ] +GET_RESPONSE = [0XA0, 0XC0, 00, 00] SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] # request any card type cardtype = AnyCardType() -cardrequest = CardRequest( timeout=5, cardType=cardtype ) +cardrequest = CardRequest(timeout=5, cardType=cardtype) cardservice = cardrequest.waitforcard() # attach the console tracer -observer=ConsoleCardConnectionObserver() -cardservice.connection.addObserver( observer ) +observer = ConsoleCardConnectionObserver() +cardservice.connection.addObserver(observer) # attach our decorator -cardservice.connection = ExclusiveTransmitCardConnection( ExclusiveConnectCardConnection( cardservice.connection ) ) +cardservice.connection = ExclusiveTransmitCardConnection(ExclusiveConnectCardConnection(cardservice.connection)) # connect to the card and perform a few transmits cardservice.connection.connect() -print 'ATR', toHexString( cardservice.connection.getATR() ) +print 'ATR', toHexString(cardservice.connection.getATR()) try: cardservice.connection.lock() - apdu = SELECT+DF_TELECOM - response, sw1, sw2 = cardservice.connection.transmit( apdu ) + apdu = SELECT + DF_TELECOM + response, sw1, sw2 = cardservice.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_RESPONSE + [sw2] - response, sw1, sw2 = cardservice.connection.transmit( apdu ) + response, sw1, sw2 = cardservice.connection.transmit(apdu) finally: cardservice.connection.unlock() import sys -if 'win32'==sys.platform: +if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorCards.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorCards.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorCards.py 2010-06-06 15:39:16 UTC (rev 431) @@ -30,17 +30,19 @@ from smartcard.CardMonitoring import CardMonitor, CardObserver from smartcard.util import * + # a simple card observer that prints inserted/removed cards -class printobserver( CardObserver ): +class printobserver(CardObserver): """A simple card observer that is notified when cards are inserted/removed from the system and prints the list of cards """ - def update( self, observable, (addedcards, removedcards) ): + + def update(self, observable, (addedcards, removedcards)): for card in addedcards: - print "+Inserted: ", toHexString( card.atr ) + print "+Inserted: ", toHexString(card.atr) for card in removedcards: - print "-Removed: ", toHexString( card.atr ) + print "-Removed: ", toHexString(card.atr) try: print "Insert or remove a smartcard in the system." @@ -48,7 +50,7 @@ print "" cardmonitor = CardMonitor() cardobserver = printobserver() - cardmonitor.addObserver( cardobserver ) + cardmonitor.addObserver(cardobserver) sleep(10) @@ -57,7 +59,7 @@ cardmonitor.deleteObserver(cardobserver) import sys - if 'win32'==sys.platform: + if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorCardsAndTransmit.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorCardsAndTransmit.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorCardsAndTransmit.py 2010-06-06 15:39:16 UTC (rev 431) @@ -1,6 +1,7 @@ #! /usr/bin/env python """ -Sample script that monitors smartcard insertion/removal and select DF_TELECOM on inserted cards +Sample script that monitors smartcard insertion/removal and select +DF_TELECOM on inserted cards __author__ = "http://www.gemalto.com" @@ -32,34 +33,35 @@ from smartcard.util import * # define the apdus used in this script -GET_RESPONSE = [0XA0, 0XC0, 00, 00 ] +GET_RESPONSE = [0XA0, 0XC0, 00, 00] SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] # a simple card observer that tries to select DF_TELECOM on an inserted card -class selectDFTELECOMObserver( CardObserver ): +class selectDFTELECOMObserver(CardObserver): """A simple card observer that is notified when cards are inserted/removed from the system and prints the list of cards """ - def __init__( self ): - self.observer=ConsoleCardConnectionObserver() - def update( self, observable, (addedcards, removedcards) ): + def __init__(self): + self.observer = ConsoleCardConnectionObserver() + + def update(self, observable, (addedcards, removedcards)): for card in addedcards: - print "+Inserted: ", toHexString( card.atr ) + print "+Inserted: ", toHexString(card.atr) card.connection = card.createConnection() card.connection.connect() - card.connection.addObserver( self.observer ) - apdu = SELECT+DF_TELECOM - response, sw1, sw2 = card.connection.transmit( apdu ) + card.connection.addObserver(self.observer) + apdu = SELECT + DF_TELECOM + response, sw1, sw2 = card.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_RESPONSE + [sw2] - response, sw1, sw2 = card.connection.transmit( apdu ) + response, sw1, sw2 = card.connection.transmit(apdu) for card in removedcards: - print "-Removed: ", toHexString( card.atr ) + print "-Removed: ", toHexString(card.atr) try: print "Insert or remove a SIM card in the system." @@ -67,16 +69,16 @@ print "" cardmonitor = CardMonitor() selectobserver = selectDFTELECOMObserver() - cardmonitor.addObserver( selectobserver ) + cardmonitor.addObserver(selectobserver) sleep(60) # don't forget to remove observer, or the # monitor will poll forever... - cardmonitor.deleteObserver( selectobserver ) + cardmonitor.deleteObserver(selectobserver) import sys - if 'win32'==sys.platform: + if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorReaders.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorReaders.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_MonitorReaders.py 2010-06-06 15:39:16 UTC (rev 431) @@ -29,13 +29,14 @@ from smartcard.ReaderMonitoring import ReaderMonitor, ReaderObserver -# a simple reader observer that prints added/removed readers -class printobserver( ReaderObserver ): + +class printobserver(ReaderObserver): """A simple reader observer that is notified when readers are added/removed from the system and prints the list of readers """ - def update( self, observable, (addedreaders, removedreaders) ): + + def update(self, observable, (addedreaders, removedreaders)): print "Added readers", addedreaders print "Removed readers", removedreaders @@ -45,7 +46,7 @@ print "" readermonitor = ReaderMonitor() readerobserver = printobserver() - readermonitor.addObserver( readerobserver ) + readermonitor.addObserver(readerobserver) sleep(10) @@ -54,7 +55,7 @@ readermonitor.deleteObserver(readerobserver) import sys - if 'win32'==sys.platform: + if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_TransmitCardObserver.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_TransmitCardObserver.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_TransmitCardObserver.py 2010-06-06 15:39:16 UTC (rev 431) @@ -30,30 +30,30 @@ from smartcard.util import * # replace by your favourite apdu -SELECT_DF_TELECOM = [0xA0, 0xA4, 0x00, 0x00, 0x02, 0x7F, 0x10 ] +SELECT_DF_TELECOM = [0xA0, 0xA4, 0x00, 0x00, 0x02, 0x7F, 0x10] -# a card observer that connects to new cards and performs a transaction, e.g. SELECT DF_TELECOM -class transmitobserver( CardObserver ): - """A card observer that is notified when cards are inserted/removed from the system, - connects to cards and SELECT DF_TELECOM - """ - def __init__( self ): - self.cards=[] - def update( self, observable, (addedcards, removedcards) ): +class transmitobserver(CardObserver): + """A card observer that is notified when cards are inserted/removed + from the system, connects to cards and SELECT DF_TELECOM """ + + def __init__(self): + self.cards = [] + + def update(self, observable, (addedcards, removedcards)): for card in addedcards: if card not in self.cards: - self.cards+=[card] - print "+Inserted: ", toHexString( card.atr ) + self.cards += [card] + print "+Inserted: ", toHexString(card.atr) card.connection = card.createConnection() card.connection.connect() - response, sw1, sw2 = card.connection.transmit( SELECT_DF_TELECOM ) + response, sw1, sw2 = card.connection.transmit(SELECT_DF_TELECOM) print "%.2x %.2x" % (sw1, sw2) for card in removedcards: - print "-Removed: ", toHexString( card.atr ) + print "-Removed: ", toHexString(card.atr) if card in self.cards: - self.cards.remove( card ) + self.cards.remove(card) try: print "Insert or remove a smartcard in the system." @@ -61,7 +61,7 @@ print "" cardmonitor = CardMonitor() cardobserver = transmitobserver() - cardmonitor.addObserver( cardobserver ) + cardmonitor.addObserver(cardobserver) sleep(100) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_apduTracerInterpreter.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_apduTracerInterpreter.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_apduTracerInterpreter.py 2010-06-06 15:39:16 UTC (rev 431) @@ -31,59 +31,60 @@ from string import replace -class TracerAndSELECTInterpreter( CardConnectionObserver ): +class TracerAndSELECTInterpreter(CardConnectionObserver): """This observer will interprer SELECT and GET RESPONSE bytes and replace them with a human readable string.""" - def update( self, cardconnection, ccevent ): - if 'connect'==ccevent.type: + def update(self, cardconnection, ccevent): + + if 'connect' == ccevent.type: print 'connecting to ' + cardconnection.getReader() - elif 'disconnect'==ccevent.type: + elif 'disconnect' == ccevent.type: print 'disconnecting from ' + cardconnection.getReader() - elif 'command'==ccevent.type: - str=toHexString(ccevent.args[0]) - str = replace( str , "A0 A4 00 00 02", "SELECT" ) - str = replace( str , "A0 C0 00 00", "GET RESPONSE" ) + elif 'command' == ccevent.type: + str = toHexString(ccevent.args[0]) + str = replace(str, "A0 A4 00 00 02", "SELECT") + str = replace(str, "A0 C0 00 00", "GET RESPONSE") print '>', str - elif 'response'==ccevent.type: - if []==ccevent.args[0]: + elif 'response' == ccevent.type: + if [] == ccevent.args[0]: print '< []', "%-2X %-2X" % tuple(ccevent.args[-2:]) else: print '<', toHexString(ccevent.args[0]), "%-2X %-2X" % tuple(ccevent.args[-2:]) # define the apdus used in this script -GET_RESPONSE = [0XA0, 0XC0, 00, 00 ] +GET_RESPONSE = [0XA0, 0XC0, 00, 00] SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02] DF_TELECOM = [0x7F, 0x10] # we request any type and wait for 10s for card insertion cardtype = AnyCardType() -cardrequest = CardRequest( timeout=10, cardType=cardtype ) +cardrequest = CardRequest(timeout=10, cardType=cardtype) cardservice = cardrequest.waitforcard() # create an instance of our observer and attach to the connection -observer=TracerAndSELECTInterpreter() -cardservice.connection.addObserver( observer ) +observer = TracerAndSELECTInterpreter() +cardservice.connection.addObserver(observer) # connect and send APDUs # the observer will trace on the console cardservice.connection.connect() -apdu = SELECT+DF_TELECOM -response, sw1, sw2 = cardservice.connection.transmit( apdu ) +apdu = SELECT + DF_TELECOM +response, sw1, sw2 = cardservice.connection.transmit(apdu) if sw1 == 0x9F: apdu = GET_RESPONSE + [sw2] - response, sw1, sw2 = cardservice.connection.transmit( apdu ) + response, sw1, sw2 = cardservice.connection.transmit(apdu) else: print 'no DF_TELECOM' import sys -if 'win32'==sys.platform: +if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) Modified: trunk/pyscard/src/smartcard/Examples/framework/sample_toHexString.py =================================================================== --- trunk/pyscard/src/smartcard/Examples/framework/sample_toHexString.py 2010-06-06 15:20:14 UTC (rev 430) +++ trunk/pyscard/src/smartcard/Examples/framework/sample_toHexString.py 2010-06-06 15:39:16 UTC (rev 431) @@ -27,31 +27,31 @@ from smartcard.util import * -print 40*'-' -bytes = [ 59, 101, 0, 0, 156, 17, 1, 1, 3] +print 40 * '-' +bytes = [59, 101, 0, 0, 156, 17, 1, 1, 3] print 'bytes = [59, 101, 0, 0, 156, 17, 1, 1, 3]' -print 'toHexString( bytes ) =', toHexString( bytes ) -print 'toHexString( bytes, COMMA ) =', toHexString( bytes, COMMA ) -print 'toHexString( bytes, PACK ) =', toHexString( bytes, PACK ) -print 'toHexString( bytes, HEX ) =', toHexString( bytes, HEX ) -print 'toHexString( bytes, HEX | COMMA ) =', toHexString( bytes, HEX | COMMA ) -print 'toHexString( bytes, HEX | UPPERCASE ) =', toHexString( bytes, HEX | UPPERCASE ) -print 'toHexString( bytes, HEX | UPPERCASE | COMMA) =', toHexString( bytes, HEX | UPPERCASE | COMMA ) +print 'toHexString(bytes) =', toHexString(bytes) +print 'toHexString(bytes, COMMA) =', toHexString(bytes, COMMA) +print 'toHexString(bytes, PACK) =', toHexString(bytes, PACK) +print 'toHexString(bytes, HEX) =', toHexString(bytes, HEX) +print 'toHexString(bytes, HEX | COMMA) =', toHexString(bytes, HEX | COMMA) +print 'toHexString(bytes, HEX | UPPERCASE) =', toHexString(bytes, HEX | UPPERCASE) +print 'toHexString(bytes, HEX | UPPERCASE | COMMA) =', toHexString(bytes, HEX | UPPERCASE | COMMA) -print 40*'-' -bytes = [ 0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03 ] +print 40 * '-' +bytes = [0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03] print 'bytes = [ 0x3B, 0x65, 0x00, 0x00, 0x9C, 0x11, 0x01, 0x01, 0x03 ]' -print 'toHexString( bytes, COMMA ) =', toHexString( bytes, COMMA ) -print 'toHexString( bytes ) =', toHexString( bytes ) -print 'toHexString( bytes, PACK ) =', toHexString( bytes, PACK ) -print 'toHexString( bytes, HEX ) =', toHexString( bytes, HEX ) -print 'toHexString( bytes, HEX | COMMA ) =', toHexString( bytes, HEX | COMMA ) -print 'toHexString( bytes, HEX | UPPERCASE ) =', toHexString( bytes, HEX | UPPERCASE ) -print 'toHexString( bytes, HEX | UPPERCASE | COMMA) =', toHexString( bytes, HEX | UPPERCASE | COMMA ) +print 'toHexString(bytes, COMMA) =', toHexString(bytes, COMMA) +print 'toHexString(bytes) =', toHexString(bytes) +print 'toHexString(bytes, PACK) =', toHexString(bytes, PACK) +print 'toHexString(bytes, HEX) =', toHexString(bytes, HEX) +print 'toHexString(bytes, HEX | COMMA) =', toHexString(bytes, HEX | COMMA) +print 'toHexString(bytes, HEX | UPPERCASE) =', toHexString(bytes, HEX | UPPERCASE) +print 'toHexString(bytes, HEX | UPPERCASE | COMMA) =', toHexString(bytes, HEX | UPPERCASE | COMMA) import sys -if 'win32'==sys.platform: +if 'win32' == sys.platform: print 'press Enter to continue' sys.stdin.read(1) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |