or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

atr-card-types.mdcard-connections.mdgui-components.mdindex.mdmonitoring.mdpcsc-interface.mdreader-management.mdsession-api.mdstatus-word-handling.mdutilities.md

session-api.mddocs/

0

# Session API

1

2

High-level smart card communication interface that provides simple session management and APDU transmission without requiring detailed knowledge of PC/SC or card connection management.

3

4

## Capabilities

5

6

### Session Class

7

8

The Session class provides the simplest way to communicate with smart cards. It automatically handles reader selection, card connection, and provides methods for APDU transmission and ATR retrieval.

9

10

```python { .api }

11

class Session:

12

def __init__(self, readerName=None):

13

"""

14

Initialize a smart card session and connect to the card.

15

16

Args:

17

readerName (str, optional): Name of the reader to connect to.

18

If None, uses the first available reader.

19

20

Raises:

21

NoReadersException: No smart card readers available

22

InvalidReaderException: Specified reader not found or invalid

23

"""

24

25

def close(self):

26

"""

27

Close the smartcard session and disconnect from the card.

28

"""

29

30

def sendCommandAPDU(self, command):

31

"""

32

Send an APDU command to the connected smart card.

33

34

Args:

35

command (list[int]): APDU command as list of bytes,

36

e.g. [0xA0, 0xA4, 0x00, 0x00, 0x02]

37

38

Returns:

39

tuple[list[int], int, int]: A tuple (response, sw1, sw2) where:

40

- response: APDU response data as list of integers

41

Note: If response length > 2, sw1 and sw2 are appended to response

42

- sw1: First status word (0x00-0xFF)

43

- sw2: Second status word (0x00-0xFF)

44

"""

45

46

def getATR(self):

47

"""

48

Get the Answer To Reset (ATR) of the connected card.

49

50

Returns:

51

list[int]: ATR bytes as list of integers

52

"""

53

54

def __repr__(self):

55

"""

56

String representation of the session.

57

58

Returns:

59

str: Session description including reader name

60

"""

61

```

62

63

### Legacy Reader Listing

64

65

Simple function for getting reader names as strings. This is maintained for backward compatibility.

66

67

```python { .api }

68

def listReaders():

69

"""

70

Get list of smart card reader names.

71

72

Returns:

73

list[str]: List of reader names as strings

74

75

Note:

76

Deprecated - Use smartcard.System.readers() instead for Reader objects.

77

"""

78

```

79

80

## Usage Examples

81

82

### Basic Session Usage

83

84

```python

85

from smartcard import Session

86

87

# Connect to first available reader

88

session = Session()

89

90

# Send a command (e.g., GET RESPONSE)

91

GET_RESPONSE = [0x00, 0xC0, 0x00, 0x00, 0x20]

92

response, sw1, sw2 = session.sendCommandAPDU(GET_RESPONSE)

93

94

print(f"Response data: {response}")

95

print(f"Status: {sw1:02X} {sw2:02X}")

96

97

# Get card ATR

98

atr = session.getATR()

99

print(f"ATR: {' '.join(f'{b:02X}' for b in atr)}")

100

101

# Clean up

102

session.close()

103

```

104

105

### Specific Reader Selection

106

107

```python

108

from smartcard import Session, listReaders

109

110

# List available readers

111

readers = listReaders()

112

print("Available readers:")

113

for i, reader in enumerate(readers):

114

print(f"{i}: {reader}")

115

116

# Connect to specific reader

117

if readers:

118

session = Session(readers[0])

119

120

# Your card operations here

121

atr = session.getATR()

122

print(f"Connected to {readers[0]}")

123

124

session.close()

125

```

126

127

### Error Handling

128

129

```python

130

from smartcard import Session

131

from smartcard.Exceptions import NoReadersException, InvalidReaderException

132

133

try:

134

session = Session("Specific Reader Name")

135

136

# Send command

137

command = [0x00, 0xA4, 0x04, 0x00, 0x07, 0xA0, 0x00, 0x00, 0x00, 0x04, 0x10, 0x10]

138

response, sw1, sw2 = session.sendCommandAPDU(command)

139

140

# Check status words

141

if sw1 == 0x90 and sw2 == 0x00:

142

print("Command successful")

143

else:

144

print(f"Command failed: {sw1:02X} {sw2:02X}")

145

146

except NoReadersException:

147

print("No smart card readers found")

148

except InvalidReaderException as e:

149

print(f"Invalid reader: {e}")

150

finally:

151

if 'session' in locals():

152

session.close()

153

```

154

155

### Context Manager Usage

156

157

```python

158

from smartcard import Session

159

160

# Manual session management (no context manager support)

161

try:

162

session = Session()

163

atr = session.getATR()

164

print(f"ATR: {' '.join(f'{b:02X}' for b in atr)}")

165

166

# Send commands...

167

response, sw1, sw2 = session.sendCommandAPDU([0x00, 0xCA, 0x9F, 0x7F, 0x00])

168

169

# Must manually close session

170

session.close()

171

172

except Exception as e:

173

print(f"Session error: {e}")

174

if 'session' in locals():

175

session.close()

176

```

177

178

## Related Types

179

180

```python { .api }

181

# Exception types that may be raised

182

class NoReadersException(SmartcardException):

183

"""Raised when no smart card readers are available."""

184

185

class InvalidReaderException(SmartcardException):

186

"""Raised when specified reader is invalid or not found."""

187

188

# Type aliases for documentation

189

ReaderName = str

190

APDUCommand = list[int]

191

APDUResponse = list[int]

192

ATRBytes = list[int]

193

StatusWord = int

194

```