blob: fee09c8dd7ff7809b10456769e20b287e5c37303 [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
Harald Weltef9f8d7a2023-07-09 17:06:16 +020024from typing import Optional
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070025
Harald Weltef9f8d7a2023-07-09 17:06:16 +020026from pySim.utils import Hexstr, ResTuple
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070027from pySim.transport import LinkBase
28from pySim.exceptions import *
29
30# HACK: if somebody needs to debug this thing
31# log.root.setLevel(log.DEBUG)
32
Harald Weltec91085e2022-02-10 18:05:45 +010033
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070034class ModemATCommandLink(LinkBase):
Harald Weltec91085e2022-02-10 18:05:45 +010035 """Transport Link for 3GPP TS 27.007 compliant modems."""
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070036
Harald Weltec91085e2022-02-10 18:05:45 +010037 def __init__(self, device: str = '/dev/ttyUSB0', baudrate: int = 115200, **kwargs):
38 super().__init__(**kwargs)
Philipp Maier30773432023-10-23 10:18:04 +020039 print("Using modem for Generic SIM Access (3GPP TS 27.007)")
Harald Weltec91085e2022-02-10 18:05:45 +010040 self._sl = serial.Serial(device, baudrate, timeout=5)
41 self._echo = False # this will be auto-detected by _check_echo()
42 self._device = device
43 self._atr = None
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020044
Harald Weltec91085e2022-02-10 18:05:45 +010045 # Check the AT interface
46 self._check_echo()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070047
Harald Weltec91085e2022-02-10 18:05:45 +010048 # Trigger initial reset
49 self.reset_card()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070050
Harald Weltec91085e2022-02-10 18:05:45 +010051 def __del__(self):
52 if hasattr(self, '_sl'):
53 self._sl.close()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070054
Harald Weltec91085e2022-02-10 18:05:45 +010055 def send_at_cmd(self, cmd, timeout=0.2, patience=0.002):
56 # Convert from string to bytes, if needed
57 bcmd = cmd if type(cmd) is bytes else cmd.encode()
58 bcmd += b'\r'
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020059
Harald Weltec91085e2022-02-10 18:05:45 +010060 # Clean input buffer from previous/unexpected data
61 self._sl.reset_input_buffer()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070062
Harald Weltec91085e2022-02-10 18:05:45 +010063 # Send command to the modem
64 log.debug('Sending AT command: %s', cmd)
65 try:
66 wlen = self._sl.write(bcmd)
67 assert(wlen == len(bcmd))
68 except:
69 raise ReaderError('Failed to send AT command: %s' % cmd)
Robert Falkenbergdddcc602021-05-06 09:55:57 +020070
Harald Weltec91085e2022-02-10 18:05:45 +010071 rsp = b''
72 its = 1
73 t_start = time.time()
74 while True:
75 rsp = rsp + self._sl.read(self._sl.in_waiting)
76 lines = rsp.split(b'\r\n')
77 if len(lines) >= 2:
78 res = lines[-2]
79 if res == b'OK':
80 log.debug('Command finished with result: %s', res)
81 break
82 if res == b'ERROR' or res.startswith(b'+CME ERROR:'):
83 log.error('Command failed with result: %s', res)
84 break
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070085
Harald Weltec91085e2022-02-10 18:05:45 +010086 if time.time() - t_start >= timeout:
87 log.info('Command finished with timeout >= %ss', timeout)
88 break
89 time.sleep(patience)
90 its += 1
91 log.debug('Command took %0.6fs (%d cycles a %fs)',
92 time.time() - t_start, its, patience)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070093
Harald Weltec91085e2022-02-10 18:05:45 +010094 if self._echo:
95 # Skip echo chars
96 rsp = rsp[wlen:]
97 rsp = rsp.strip()
98 rsp = rsp.split(b'\r\n\r\n')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070099
Harald Weltec91085e2022-02-10 18:05:45 +0100100 log.debug('Got response from modem: %s', rsp)
101 return rsp
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700102
Harald Weltec91085e2022-02-10 18:05:45 +0100103 def _check_echo(self):
104 """Verify the correct response to 'AT' command
105 and detect if inputs are echoed by the device
Robert Falkenberg18fb82b2021-05-02 10:21:23 +0200106
Harald Weltec91085e2022-02-10 18:05:45 +0100107 Although echo of inputs can be enabled/disabled via
108 ATE1/ATE0, respectively, we rather detect the current
109 configuration of the modem without any change.
110 """
111 # Next command shall not strip the echo from the response
112 self._echo = False
113 result = self.send_at_cmd('AT')
Robert Falkenberg18fb82b2021-05-02 10:21:23 +0200114
Harald Weltec91085e2022-02-10 18:05:45 +0100115 # Verify the response
116 if len(result) > 0:
117 if result[-1] == b'OK':
118 self._echo = False
119 return
120 elif result[-1] == b'AT\r\r\nOK':
121 self._echo = True
122 return
123 raise ReaderError(
124 'Interface \'%s\' does not respond to \'AT\' command' % self._device)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700125
Harald Weltec91085e2022-02-10 18:05:45 +0100126 def reset_card(self):
127 # Reset the modem, just to be sure
128 if self.send_at_cmd('ATZ') != [b'OK']:
129 raise ReaderError('Failed to reset the modem')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700130
Harald Weltec91085e2022-02-10 18:05:45 +0100131 # Make sure that generic SIM access is supported
132 if self.send_at_cmd('AT+CSIM=?') != [b'OK']:
133 raise ReaderError('The modem does not seem to support SIM access')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700134
Harald Weltec91085e2022-02-10 18:05:45 +0100135 log.info('Modem at \'%s\' is ready!' % self._device)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700136
Harald Weltec91085e2022-02-10 18:05:45 +0100137 def connect(self):
138 pass # Nothing to do really ...
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700139
Harald Weltec91085e2022-02-10 18:05:45 +0100140 def disconnect(self):
141 pass # Nothing to do really ...
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700142
Harald Welteab6897c2023-07-09 16:21:23 +0200143 def wait_for_card(self, timeout: Optional[int] = None, newcardonly: bool = False):
Harald Weltec91085e2022-02-10 18:05:45 +0100144 pass # Nothing to do really ...
Robert Falkenberg8e15c182021-05-01 08:07:27 +0200145
Harald Weltef9f8d7a2023-07-09 17:06:16 +0200146 def _send_apdu_raw(self, pdu: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100147 # Make sure pdu has upper case hex digits [A-F]
148 pdu = pdu.upper()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700149
Harald Weltec91085e2022-02-10 18:05:45 +0100150 # Prepare the command as described in 8.17
151 cmd = 'AT+CSIM=%d,\"%s\"' % (len(pdu), pdu)
152 log.debug('Sending command: %s', cmd)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700153
Harald Weltec91085e2022-02-10 18:05:45 +0100154 # Send AT+CSIM command to the modem
Harald Weltec91085e2022-02-10 18:05:45 +0100155 rsp = self.send_at_cmd(cmd)
Tobias Engeld70ac222023-05-29 21:20:59 +0200156 if rsp[-1].startswith(b'+CME ERROR:'):
157 raise ProtocolError('AT+CSIM failed with: %s' % str(rsp))
Harald Weltec91085e2022-02-10 18:05:45 +0100158 if len(rsp) != 2 or rsp[-1] != b'OK':
159 raise ReaderError('APDU transfer failed: %s' % str(rsp))
160 rsp = rsp[0] # Get rid of b'OK'
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700161
Harald Weltec91085e2022-02-10 18:05:45 +0100162 # Make sure that the response has format: b'+CSIM: %d,\"%s\"'
163 try:
164 result = re.match(b'\+CSIM: (\d+),\"([0-9A-F]+)\"', rsp)
165 (rsp_pdu_len, rsp_pdu) = result.groups()
166 except:
167 raise ReaderError('Failed to parse response from modem: %s' % rsp)
168
169 # TODO: make sure we have at least SW
170 data = rsp_pdu[:-4].decode().lower()
171 sw = rsp_pdu[-4:].decode().lower()
172 log.debug('Command response: %s, %s', data, sw)
173 return data, sw
Philipp Maier6bfa8a82023-10-09 13:32:49 +0200174
Philipp Maier58e89eb2023-10-10 11:59:03 +0200175 def __str__(self) -> str:
Philipp Maier6bfa8a82023-10-09 13:32:49 +0200176 return "modem:%s" % self._device
Philipp Maier8c823782023-10-23 10:44:44 +0200177
178 @staticmethod
179 def argparse_add_reader_args(arg_parser: argparse.ArgumentParser):
180 modem_group = arg_parser.add_argument_group('AT Command Modem Reader')
181 modem_group.add_argument('--modem-device', dest='modem_dev', metavar='DEV', default=None,
182 help='Serial port of modem for Generic SIM Access (3GPP TS 27.007)')
183 modem_group.add_argument('--modem-baud', type=int, metavar='BAUD', default=115200,
184 help='Baud rate used for modem port')