Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 3 | # 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 Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 19 | import logging as log |
| 20 | import serial |
| 21 | import time |
| 22 | import re |
| 23 | |
| 24 | from pySim.transport import LinkBase |
| 25 | from pySim.exceptions import * |
| 26 | |
| 27 | # HACK: if somebody needs to debug this thing |
| 28 | # log.root.setLevel(log.DEBUG) |
| 29 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 30 | |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 31 | class ModemATCommandLink(LinkBase): |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 32 | """Transport Link for 3GPP TS 27.007 compliant modems.""" |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 33 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 34 | def __init__(self, device: str = '/dev/ttyUSB0', baudrate: int = 115200, **kwargs): |
| 35 | super().__init__(**kwargs) |
| 36 | self._sl = serial.Serial(device, baudrate, timeout=5) |
| 37 | self._echo = False # this will be auto-detected by _check_echo() |
| 38 | self._device = device |
| 39 | self._atr = None |
Robert Falkenberg | 18fb82b | 2021-05-02 10:21:23 +0200 | [diff] [blame] | 40 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 41 | # Check the AT interface |
| 42 | self._check_echo() |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 43 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 44 | # Trigger initial reset |
| 45 | self.reset_card() |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 46 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 47 | def __del__(self): |
| 48 | if hasattr(self, '_sl'): |
| 49 | self._sl.close() |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 50 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 51 | def send_at_cmd(self, cmd, timeout=0.2, patience=0.002): |
| 52 | # Convert from string to bytes, if needed |
| 53 | bcmd = cmd if type(cmd) is bytes else cmd.encode() |
| 54 | bcmd += b'\r' |
Robert Falkenberg | 18fb82b | 2021-05-02 10:21:23 +0200 | [diff] [blame] | 55 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 56 | # Clean input buffer from previous/unexpected data |
| 57 | self._sl.reset_input_buffer() |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 58 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 59 | # Send command to the modem |
| 60 | log.debug('Sending AT command: %s', cmd) |
| 61 | try: |
| 62 | wlen = self._sl.write(bcmd) |
| 63 | assert(wlen == len(bcmd)) |
| 64 | except: |
| 65 | raise ReaderError('Failed to send AT command: %s' % cmd) |
Robert Falkenberg | dddcc60 | 2021-05-06 09:55:57 +0200 | [diff] [blame] | 66 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 67 | rsp = b'' |
| 68 | its = 1 |
| 69 | t_start = time.time() |
| 70 | while True: |
| 71 | rsp = rsp + self._sl.read(self._sl.in_waiting) |
| 72 | lines = rsp.split(b'\r\n') |
| 73 | if len(lines) >= 2: |
| 74 | res = lines[-2] |
| 75 | if res == b'OK': |
| 76 | log.debug('Command finished with result: %s', res) |
| 77 | break |
| 78 | if res == b'ERROR' or res.startswith(b'+CME ERROR:'): |
| 79 | log.error('Command failed with result: %s', res) |
| 80 | break |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 81 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 82 | if time.time() - t_start >= timeout: |
| 83 | log.info('Command finished with timeout >= %ss', timeout) |
| 84 | break |
| 85 | time.sleep(patience) |
| 86 | its += 1 |
| 87 | log.debug('Command took %0.6fs (%d cycles a %fs)', |
| 88 | time.time() - t_start, its, patience) |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 89 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 90 | if self._echo: |
| 91 | # Skip echo chars |
| 92 | rsp = rsp[wlen:] |
| 93 | rsp = rsp.strip() |
| 94 | rsp = rsp.split(b'\r\n\r\n') |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 95 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 96 | log.debug('Got response from modem: %s', rsp) |
| 97 | return rsp |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 98 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 99 | def _check_echo(self): |
| 100 | """Verify the correct response to 'AT' command |
| 101 | and detect if inputs are echoed by the device |
Robert Falkenberg | 18fb82b | 2021-05-02 10:21:23 +0200 | [diff] [blame] | 102 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 103 | Although echo of inputs can be enabled/disabled via |
| 104 | ATE1/ATE0, respectively, we rather detect the current |
| 105 | configuration of the modem without any change. |
| 106 | """ |
| 107 | # Next command shall not strip the echo from the response |
| 108 | self._echo = False |
| 109 | result = self.send_at_cmd('AT') |
Robert Falkenberg | 18fb82b | 2021-05-02 10:21:23 +0200 | [diff] [blame] | 110 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 111 | # Verify the response |
| 112 | if len(result) > 0: |
| 113 | if result[-1] == b'OK': |
| 114 | self._echo = False |
| 115 | return |
| 116 | elif result[-1] == b'AT\r\r\nOK': |
| 117 | self._echo = True |
| 118 | return |
| 119 | raise ReaderError( |
| 120 | 'Interface \'%s\' does not respond to \'AT\' command' % self._device) |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 121 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 122 | def reset_card(self): |
| 123 | # Reset the modem, just to be sure |
| 124 | if self.send_at_cmd('ATZ') != [b'OK']: |
| 125 | raise ReaderError('Failed to reset the modem') |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 126 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 127 | # Make sure that generic SIM access is supported |
| 128 | if self.send_at_cmd('AT+CSIM=?') != [b'OK']: |
| 129 | raise ReaderError('The modem does not seem to support SIM access') |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 130 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 131 | log.info('Modem at \'%s\' is ready!' % self._device) |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 132 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 133 | def connect(self): |
| 134 | pass # Nothing to do really ... |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 135 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 136 | def disconnect(self): |
| 137 | pass # Nothing to do really ... |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 138 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 139 | def wait_for_card(self, timeout=None, newcardonly=False): |
| 140 | pass # Nothing to do really ... |
Robert Falkenberg | 8e15c18 | 2021-05-01 08:07:27 +0200 | [diff] [blame] | 141 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 142 | def _send_apdu_raw(self, pdu): |
| 143 | # Make sure pdu has upper case hex digits [A-F] |
| 144 | pdu = pdu.upper() |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 145 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 146 | # Prepare the command as described in 8.17 |
| 147 | cmd = 'AT+CSIM=%d,\"%s\"' % (len(pdu), pdu) |
| 148 | log.debug('Sending command: %s', cmd) |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 149 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 150 | # Send AT+CSIM command to the modem |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 151 | rsp = self.send_at_cmd(cmd) |
Tobias Engel | d70ac22 | 2023-05-29 21:20:59 +0200 | [diff] [blame^] | 152 | if rsp[-1].startswith(b'+CME ERROR:'): |
| 153 | raise ProtocolError('AT+CSIM failed with: %s' % str(rsp)) |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 154 | if len(rsp) != 2 or rsp[-1] != b'OK': |
| 155 | raise ReaderError('APDU transfer failed: %s' % str(rsp)) |
| 156 | rsp = rsp[0] # Get rid of b'OK' |
Vadim Yanitskiy | 29ca804 | 2020-05-09 21:23:37 +0700 | [diff] [blame] | 157 | |
Harald Welte | c91085e | 2022-02-10 18:05:45 +0100 | [diff] [blame] | 158 | # Make sure that the response has format: b'+CSIM: %d,\"%s\"' |
| 159 | try: |
| 160 | result = re.match(b'\+CSIM: (\d+),\"([0-9A-F]+)\"', rsp) |
| 161 | (rsp_pdu_len, rsp_pdu) = result.groups() |
| 162 | except: |
| 163 | raise ReaderError('Failed to parse response from modem: %s' % rsp) |
| 164 | |
| 165 | # TODO: make sure we have at least SW |
| 166 | data = rsp_pdu[:-4].decode().lower() |
| 167 | sw = rsp_pdu[-4:].decode().lower() |
| 168 | log.debug('Command response: %s, %s', data, sw) |
| 169 | return data, sw |