blob: e99762ddc553db1c78cf1efa1d4169c1b94db533 [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
Harald Weltef9f8d7a2023-07-09 17:06:16 +020023from typing import Optional
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070024
Harald Weltef9f8d7a2023-07-09 17:06:16 +020025from pySim.utils import Hexstr, ResTuple
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070026from pySim.transport import LinkBase
27from pySim.exceptions import *
28
29# HACK: if somebody needs to debug this thing
30# log.root.setLevel(log.DEBUG)
31
Harald Weltec91085e2022-02-10 18:05:45 +010032
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070033class ModemATCommandLink(LinkBase):
Harald Weltec91085e2022-02-10 18:05:45 +010034 """Transport Link for 3GPP TS 27.007 compliant modems."""
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070035
Harald Weltec91085e2022-02-10 18:05:45 +010036 def __init__(self, device: str = '/dev/ttyUSB0', baudrate: int = 115200, **kwargs):
37 super().__init__(**kwargs)
38 self._sl = serial.Serial(device, baudrate, timeout=5)
39 self._echo = False # this will be auto-detected by _check_echo()
40 self._device = device
41 self._atr = None
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020042
Harald Weltec91085e2022-02-10 18:05:45 +010043 # Check the AT interface
44 self._check_echo()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070045
Harald Weltec91085e2022-02-10 18:05:45 +010046 # Trigger initial reset
47 self.reset_card()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070048
Harald Weltec91085e2022-02-10 18:05:45 +010049 def __del__(self):
50 if hasattr(self, '_sl'):
51 self._sl.close()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070052
Harald Weltec91085e2022-02-10 18:05:45 +010053 def send_at_cmd(self, cmd, timeout=0.2, patience=0.002):
54 # Convert from string to bytes, if needed
55 bcmd = cmd if type(cmd) is bytes else cmd.encode()
56 bcmd += b'\r'
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020057
Harald Weltec91085e2022-02-10 18:05:45 +010058 # Clean input buffer from previous/unexpected data
59 self._sl.reset_input_buffer()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070060
Harald Weltec91085e2022-02-10 18:05:45 +010061 # Send command to the modem
62 log.debug('Sending AT command: %s', cmd)
63 try:
64 wlen = self._sl.write(bcmd)
65 assert(wlen == len(bcmd))
66 except:
67 raise ReaderError('Failed to send AT command: %s' % cmd)
Robert Falkenbergdddcc602021-05-06 09:55:57 +020068
Harald Weltec91085e2022-02-10 18:05:45 +010069 rsp = b''
70 its = 1
71 t_start = time.time()
72 while True:
73 rsp = rsp + self._sl.read(self._sl.in_waiting)
74 lines = rsp.split(b'\r\n')
75 if len(lines) >= 2:
76 res = lines[-2]
77 if res == b'OK':
78 log.debug('Command finished with result: %s', res)
79 break
80 if res == b'ERROR' or res.startswith(b'+CME ERROR:'):
81 log.error('Command failed with result: %s', res)
82 break
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070083
Harald Weltec91085e2022-02-10 18:05:45 +010084 if time.time() - t_start >= timeout:
85 log.info('Command finished with timeout >= %ss', timeout)
86 break
87 time.sleep(patience)
88 its += 1
89 log.debug('Command took %0.6fs (%d cycles a %fs)',
90 time.time() - t_start, its, patience)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070091
Harald Weltec91085e2022-02-10 18:05:45 +010092 if self._echo:
93 # Skip echo chars
94 rsp = rsp[wlen:]
95 rsp = rsp.strip()
96 rsp = rsp.split(b'\r\n\r\n')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070097
Harald Weltec91085e2022-02-10 18:05:45 +010098 log.debug('Got response from modem: %s', rsp)
99 return rsp
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700100
Harald Weltec91085e2022-02-10 18:05:45 +0100101 def _check_echo(self):
102 """Verify the correct response to 'AT' command
103 and detect if inputs are echoed by the device
Robert Falkenberg18fb82b2021-05-02 10:21:23 +0200104
Harald Weltec91085e2022-02-10 18:05:45 +0100105 Although echo of inputs can be enabled/disabled via
106 ATE1/ATE0, respectively, we rather detect the current
107 configuration of the modem without any change.
108 """
109 # Next command shall not strip the echo from the response
110 self._echo = False
111 result = self.send_at_cmd('AT')
Robert Falkenberg18fb82b2021-05-02 10:21:23 +0200112
Harald Weltec91085e2022-02-10 18:05:45 +0100113 # Verify the response
114 if len(result) > 0:
115 if result[-1] == b'OK':
116 self._echo = False
117 return
118 elif result[-1] == b'AT\r\r\nOK':
119 self._echo = True
120 return
121 raise ReaderError(
122 'Interface \'%s\' does not respond to \'AT\' command' % self._device)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700123
Harald Weltec91085e2022-02-10 18:05:45 +0100124 def reset_card(self):
125 # Reset the modem, just to be sure
126 if self.send_at_cmd('ATZ') != [b'OK']:
127 raise ReaderError('Failed to reset the modem')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700128
Harald Weltec91085e2022-02-10 18:05:45 +0100129 # Make sure that generic SIM access is supported
130 if self.send_at_cmd('AT+CSIM=?') != [b'OK']:
131 raise ReaderError('The modem does not seem to support SIM access')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700132
Harald Weltec91085e2022-02-10 18:05:45 +0100133 log.info('Modem at \'%s\' is ready!' % self._device)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700134
Harald Weltec91085e2022-02-10 18:05:45 +0100135 def connect(self):
136 pass # Nothing to do really ...
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700137
Harald Weltec91085e2022-02-10 18:05:45 +0100138 def disconnect(self):
139 pass # Nothing to do really ...
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700140
Harald Welteab6897c2023-07-09 16:21:23 +0200141 def wait_for_card(self, timeout: Optional[int] = None, newcardonly: bool = False):
Harald Weltec91085e2022-02-10 18:05:45 +0100142 pass # Nothing to do really ...
Robert Falkenberg8e15c182021-05-01 08:07:27 +0200143
Harald Weltef9f8d7a2023-07-09 17:06:16 +0200144 def _send_apdu_raw(self, pdu: Hexstr) -> ResTuple:
Harald Weltec91085e2022-02-10 18:05:45 +0100145 # Make sure pdu has upper case hex digits [A-F]
146 pdu = pdu.upper()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700147
Harald Weltec91085e2022-02-10 18:05:45 +0100148 # Prepare the command as described in 8.17
149 cmd = 'AT+CSIM=%d,\"%s\"' % (len(pdu), pdu)
150 log.debug('Sending command: %s', cmd)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700151
Harald Weltec91085e2022-02-10 18:05:45 +0100152 # Send AT+CSIM command to the modem
Harald Weltec91085e2022-02-10 18:05:45 +0100153 rsp = self.send_at_cmd(cmd)
Tobias Engeld70ac222023-05-29 21:20:59 +0200154 if rsp[-1].startswith(b'+CME ERROR:'):
155 raise ProtocolError('AT+CSIM failed with: %s' % str(rsp))
Harald Weltec91085e2022-02-10 18:05:45 +0100156 if len(rsp) != 2 or rsp[-1] != b'OK':
157 raise ReaderError('APDU transfer failed: %s' % str(rsp))
158 rsp = rsp[0] # Get rid of b'OK'
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700159
Harald Weltec91085e2022-02-10 18:05:45 +0100160 # Make sure that the response has format: b'+CSIM: %d,\"%s\"'
161 try:
162 result = re.match(b'\+CSIM: (\d+),\"([0-9A-F]+)\"', rsp)
163 (rsp_pdu_len, rsp_pdu) = result.groups()
164 except:
165 raise ReaderError('Failed to parse response from modem: %s' % rsp)
166
167 # TODO: make sure we have at least SW
168 data = rsp_pdu[:-4].decode().lower()
169 sw = rsp_pdu[-4:].decode().lower()
170 log.debug('Command response: %s, %s', data, sw)
171 return data, sw