blob: 71f76e20f5d6afa006361359039359a8ee8fbc41 [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
Philipp Maier8c823782023-10-23 10:44:44 +020023import argparse
Philipp Maier4af63dc2023-10-26 12:17:32 +020024import os
Harald Weltef9f8d7a2023-07-09 17:06:16 +020025from typing import Optional
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070026
Harald Weltef9f8d7a2023-07-09 17:06:16 +020027from pySim.utils import Hexstr, ResTuple
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070028from pySim.transport import LinkBase
29from pySim.exceptions import *
30
31# HACK: if somebody needs to debug this thing
32# log.root.setLevel(log.DEBUG)
33
Harald Weltec91085e2022-02-10 18:05:45 +010034
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070035class ModemATCommandLink(LinkBase):
Harald Weltec91085e2022-02-10 18:05:45 +010036 """Transport Link for 3GPP TS 27.007 compliant modems."""
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070037
Harald Weltec91085e2022-02-10 18:05:45 +010038 def __init__(self, device: str = '/dev/ttyUSB0', baudrate: int = 115200, **kwargs):
39 super().__init__(**kwargs)
Philipp Maier4af63dc2023-10-26 12:17:32 +020040 if os.environ.get('PYSIM_INTEGRATION_TEST') == "1":
41 print("Using modem for Generic SIM Access (3GPP TS 27.007)")
42 else:
43 print("Using modem for Generic SIM Access (3GPP TS 27.007) at port %s" % device)
Harald Weltec91085e2022-02-10 18:05:45 +010044 self._sl = serial.Serial(device, baudrate, timeout=5)
45 self._echo = False # this will be auto-detected by _check_echo()
46 self._device = device
47 self._atr = None
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020048
Harald Weltec91085e2022-02-10 18:05:45 +010049 # Check the AT interface
50 self._check_echo()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070051
Harald Weltec91085e2022-02-10 18:05:45 +010052 # Trigger initial reset
53 self.reset_card()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070054
Harald Weltec91085e2022-02-10 18:05:45 +010055 def __del__(self):
56 if hasattr(self, '_sl'):
57 self._sl.close()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070058
Harald Weltec91085e2022-02-10 18:05:45 +010059 def send_at_cmd(self, cmd, timeout=0.2, patience=0.002):
60 # Convert from string to bytes, if needed
61 bcmd = cmd if type(cmd) is bytes else cmd.encode()
62 bcmd += b'\r'
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020063
Harald Weltec91085e2022-02-10 18:05:45 +010064 # Clean input buffer from previous/unexpected data
65 self._sl.reset_input_buffer()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070066
Harald Weltec91085e2022-02-10 18:05:45 +010067 # Send command to the modem
68 log.debug('Sending AT command: %s', cmd)
69 try:
70 wlen = self._sl.write(bcmd)
71 assert(wlen == len(bcmd))
72 except:
73 raise ReaderError('Failed to send AT command: %s' % cmd)
Robert Falkenbergdddcc602021-05-06 09:55:57 +020074
Harald Weltec91085e2022-02-10 18:05:45 +010075 rsp = b''
76 its = 1
77 t_start = time.time()
78 while True:
79 rsp = rsp + self._sl.read(self._sl.in_waiting)
80 lines = rsp.split(b'\r\n')
81 if len(lines) >= 2:
82 res = lines[-2]
83 if res == b'OK':
84 log.debug('Command finished with result: %s', res)
85 break
86 if res == b'ERROR' or res.startswith(b'+CME ERROR:'):
87 log.error('Command failed with result: %s', res)
88 break
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070089
Harald Weltec91085e2022-02-10 18:05:45 +010090 if time.time() - t_start >= timeout:
91 log.info('Command finished with timeout >= %ss', timeout)
92 break
93 time.sleep(patience)
94 its += 1
95 log.debug('Command took %0.6fs (%d cycles a %fs)',
96 time.time() - t_start, its, patience)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070097
Harald Weltec91085e2022-02-10 18:05:45 +010098 if self._echo:
99 # Skip echo chars
100 rsp = rsp[wlen:]
101 rsp = rsp.strip()
102 rsp = rsp.split(b'\r\n\r\n')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700103
Harald Weltec91085e2022-02-10 18:05:45 +0100104 log.debug('Got response from modem: %s', rsp)
105 return rsp
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700106
Harald Weltec91085e2022-02-10 18:05:45 +0100107 def _check_echo(self):
108 """Verify the correct response to 'AT' command
109 and detect if inputs are echoed by the device
Robert Falkenberg18fb82b2021-05-02 10:21:23 +0200110
Harald Weltec91085e2022-02-10 18:05:45 +0100111 Although echo of inputs can be enabled/disabled via
112 ATE1/ATE0, respectively, we rather detect the current
113 configuration of the modem without any change.
114 """
115 # Next command shall not strip the echo from the response
116 self._echo = False
117 result = self.send_at_cmd('AT')
Robert Falkenberg18fb82b2021-05-02 10:21:23 +0200118
Harald Weltec91085e2022-02-10 18:05:45 +0100119 # Verify the response
120 if len(result) > 0:
121 if result[-1] == b'OK':
122 self._echo = False
123 return
124 elif result[-1] == b'AT\r\r\nOK':
125 self._echo = True
126 return
127 raise ReaderError(
128 'Interface \'%s\' does not respond to \'AT\' command' % self._device)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700129
Harald Weltec91085e2022-02-10 18:05:45 +0100130 def reset_card(self):
131 # Reset the modem, just to be sure
132 if self.send_at_cmd('ATZ') != [b'OK']:
133 raise ReaderError('Failed to reset the modem')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700134
Harald Weltec91085e2022-02-10 18:05:45 +0100135 # Make sure that generic SIM access is supported
136 if self.send_at_cmd('AT+CSIM=?') != [b'OK']:
137 raise ReaderError('The modem does not seem to support SIM access')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700138
Harald Weltec91085e2022-02-10 18:05:45 +0100139 log.info('Modem at \'%s\' is ready!' % self._device)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700140
Harald Weltec91085e2022-02-10 18:05:45 +0100141 def connect(self):
142 pass # Nothing to do really ...
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700143
Harald Weltec91085e2022-02-10 18:05:45 +0100144 def disconnect(self):
145 pass # Nothing to do really ...
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700146
Harald Welteab6897c2023-07-09 16:21:23 +0200147 def wait_for_card(self, timeout: Optional[int] = None, newcardonly: bool = False):
Harald Weltec91085e2022-02-10 18:05:45 +0100148 pass # Nothing to do really ...
Robert Falkenberg8e15c182021-05-01 08:07:27 +0200149
Harald Weltef9f8d7a2023-07-09 17:06:16 +0200150 def _send_apdu_raw(self, pdu: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100151 # Make sure pdu has upper case hex digits [A-F]
152 pdu = pdu.upper()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700153
Harald Weltec91085e2022-02-10 18:05:45 +0100154 # Prepare the command as described in 8.17
155 cmd = 'AT+CSIM=%d,\"%s\"' % (len(pdu), pdu)
156 log.debug('Sending command: %s', cmd)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700157
Harald Weltec91085e2022-02-10 18:05:45 +0100158 # Send AT+CSIM command to the modem
Harald Weltec91085e2022-02-10 18:05:45 +0100159 rsp = self.send_at_cmd(cmd)
Tobias Engeld70ac222023-05-29 21:20:59 +0200160 if rsp[-1].startswith(b'+CME ERROR:'):
161 raise ProtocolError('AT+CSIM failed with: %s' % str(rsp))
Harald Weltec91085e2022-02-10 18:05:45 +0100162 if len(rsp) != 2 or rsp[-1] != b'OK':
163 raise ReaderError('APDU transfer failed: %s' % str(rsp))
164 rsp = rsp[0] # Get rid of b'OK'
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700165
Harald Weltec91085e2022-02-10 18:05:45 +0100166 # Make sure that the response has format: b'+CSIM: %d,\"%s\"'
167 try:
168 result = re.match(b'\+CSIM: (\d+),\"([0-9A-F]+)\"', rsp)
169 (rsp_pdu_len, rsp_pdu) = result.groups()
170 except:
171 raise ReaderError('Failed to parse response from modem: %s' % rsp)
172
173 # TODO: make sure we have at least SW
174 data = rsp_pdu[:-4].decode().lower()
175 sw = rsp_pdu[-4:].decode().lower()
176 log.debug('Command response: %s, %s', data, sw)
177 return data, sw
Philipp Maier6bfa8a82023-10-09 13:32:49 +0200178
Philipp Maier58e89eb2023-10-10 11:59:03 +0200179 def __str__(self) -> str:
Philipp Maier6bfa8a82023-10-09 13:32:49 +0200180 return "modem:%s" % self._device
Philipp Maier8c823782023-10-23 10:44:44 +0200181
182 @staticmethod
183 def argparse_add_reader_args(arg_parser: argparse.ArgumentParser):
184 modem_group = arg_parser.add_argument_group('AT Command Modem Reader')
185 modem_group.add_argument('--modem-device', dest='modem_dev', metavar='DEV', default=None,
186 help='Serial port of modem for Generic SIM Access (3GPP TS 27.007)')
187 modem_group.add_argument('--modem-baud', type=int, metavar='BAUD', default=115200,
188 help='Baud rate used for modem port')