blob: 43614f1ac5c0eb681dc7f915dc78ebac2824a699 [file] [log] [blame]
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +07001# -*- coding: utf-8 -*-
2
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +07003# Copyright (C) 2020 Vadim Yanitskiy <axilirator@gmail.com>
4#
5# This program is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 2 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program. If not, see <http://www.gnu.org/licenses/>.
17#
18
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070019import logging as log
20import serial
21import time
22import re
23
24from pySim.transport import LinkBase
25from pySim.exceptions import *
26
27# HACK: if somebody needs to debug this thing
28# log.root.setLevel(log.DEBUG)
29
30class ModemATCommandLink(LinkBase):
Harald Welteee3501f2021-04-02 13:00:18 +020031 """Transport Link for 3GPP TS 27.007 compliant modems."""
Harald Welteeb05b2f2021-04-10 11:01:56 +020032 def __init__(self, device:str='/dev/ttyUSB0', baudrate:int=115200, **kwargs):
33 super().__init__(**kwargs)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070034 self._sl = serial.Serial(device, baudrate, timeout=5)
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020035 self._echo = False # this will be auto-detected by _check_echo()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070036 self._device = device
37 self._atr = None
38
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020039 # Check the AT interface
40 self._check_echo()
41
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070042 # Trigger initial reset
43 self.reset_card()
44
45 def __del__(self):
46 self._sl.close()
47
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020048 def send_at_cmd(self, cmd, timeout=0.2, patience=0.002):
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070049 # Convert from string to bytes, if needed
50 bcmd = cmd if type(cmd) is bytes else cmd.encode()
51 bcmd += b'\r'
52
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020053 # Clean input buffer from previous/unexpected data
54 self._sl.reset_input_buffer()
55
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070056 # Send command to the modem
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020057 log.debug('Sending AT command: %s', cmd)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070058 try:
59 wlen = self._sl.write(bcmd)
60 assert(wlen == len(bcmd))
61 except:
62 raise ReaderError('Failed to send AT command: %s' % cmd)
63
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020064 rsp = b''
65 its = 1
66 t_start = time.time()
67 while True:
68 rsp = rsp + self._sl.read(self._sl.in_waiting)
69 if rsp.endswith(b'OK\r\n'):
70 log.debug('Command finished with result: OK')
71 break
72 if rsp.endswith(b'ERROR\r\n'):
73 log.debug('Command finished with result: ERROR')
74 break
75 if time.time() - t_start >= timeout:
76 log.debug('Command finished with timeout >= %ss', timeout)
77 break
78 time.sleep(patience)
79 its += 1
80 log.debug('Command took %0.6fs (%d cycles a %fs)', time.time() - t_start, its, patience)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070081
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020082 if self._echo:
83 # Skip echo chars
84 rsp = rsp[wlen:]
85 rsp = rsp.strip()
86 rsp = rsp.split(b'\r\n\r\n')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070087
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020088 log.debug('Got response from modem: %s', rsp)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070089 return rsp
90
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020091 def _check_echo(self):
92 """Verify the correct response to 'AT' command
93 and detect if inputs are echoed by the device
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070094
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020095 Although echo of inputs can be enabled/disabled via
96 ATE1/ATE0, respectively, we rather detect the current
97 configuration of the modem without any change.
98 """
99 # Next command shall not strip the echo from the response
100 self._echo = False
101 result = self.send_at_cmd('AT')
102
103 # Verify the response
104 if len(result) > 0:
105 if result[-1] == b'OK':
106 self._echo = False
107 return
108 elif result[-1] == b'AT\r\r\nOK':
109 self._echo = True
110 return
111 raise ReaderError('Interface \'%s\' does not respond to \'AT\' command' % self._device)
112
113 def reset_card(self):
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700114 # Reset the modem, just to be sure
115 if self.send_at_cmd('ATZ') != [b'OK']:
116 raise ReaderError('Failed to reset the modem')
117
118 # Make sure that generic SIM access is supported
119 if self.send_at_cmd('AT+CSIM=?') != [b'OK']:
120 raise ReaderError('The modem does not seem to support SIM access')
121
122 log.info('Modem at \'%s\' is ready!' % self._device)
123
124 def connect(self):
125 pass # Nothing to do really ...
126
127 def disconnect(self):
128 pass # Nothing to do really ...
129
130 def wait_for_card(self, timeout=None, newcardonly=False):
131 pass # Nothing to do really ...
132
Harald Weltec34f9402021-04-10 10:55:24 +0200133 def _send_apdu_raw(self, pdu):
Robert Falkenberg8e15c182021-05-01 08:07:27 +0200134 # Make sure pdu has upper case hex digits [A-F]
135 pdu = pdu.upper()
136
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700137 # Prepare the command as described in 8.17
138 cmd = 'AT+CSIM=%d,\"%s\"' % (len(pdu), pdu)
139
140 # Send AT+CSIM command to the modem
141 # TODO: also handle +CME ERROR: <err>
142 rsp = self.send_at_cmd(cmd)
143 if len(rsp) != 2 or rsp[-1] != b'OK':
144 raise ReaderError('APDU transfer failed: %s' % str(rsp))
145 rsp = rsp[0] # Get rid of b'OK'
146
147 # Make sure that the response has format: b'+CSIM: %d,\"%s\"'
148 try:
149 result = re.match(b'\+CSIM: (\d+),\"([0-9A-F]+)\"', rsp)
150 (rsp_pdu_len, rsp_pdu) = result.groups()
151 except:
152 raise ReaderError('Failed to parse response from modem: %s' % rsp)
153
154 # TODO: make sure we have at least SW
155 data = rsp_pdu[:-4].decode()
156 sw = rsp_pdu[-4:].decode()
157 return data, sw