blob: 04f922102713f0f782cdea593e2536562d77dbea [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):
Vadim Yanitskiy52efc032021-05-02 23:07:38 +020046 if hasattr(self, '_sl'):
47 self._sl.close()
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070048
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020049 def send_at_cmd(self, cmd, timeout=0.2, patience=0.002):
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070050 # Convert from string to bytes, if needed
51 bcmd = cmd if type(cmd) is bytes else cmd.encode()
52 bcmd += b'\r'
53
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020054 # Clean input buffer from previous/unexpected data
55 self._sl.reset_input_buffer()
56
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070057 # Send command to the modem
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020058 log.debug('Sending AT command: %s', cmd)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070059 try:
60 wlen = self._sl.write(bcmd)
61 assert(wlen == len(bcmd))
62 except:
63 raise ReaderError('Failed to send AT command: %s' % cmd)
64
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020065 rsp = b''
66 its = 1
67 t_start = time.time()
68 while True:
69 rsp = rsp + self._sl.read(self._sl.in_waiting)
Robert Falkenbergdddcc602021-05-06 09:55:57 +020070 lines = rsp.split(b'\r\n')
71 if len(lines) >= 2:
72 res = lines[-2]
73 if res == b'OK':
74 log.debug('Command finished with result: %s', res)
75 break
76 if res == b'ERROR' or res.startswith(b'+CME ERROR:'):
77 log.error('Command failed with result: %s', res)
78 break
79
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020080 if time.time() - t_start >= timeout:
Robert Falkenberg7cb7c782021-05-06 09:52:31 +020081 log.info('Command finished with timeout >= %ss', timeout)
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020082 break
83 time.sleep(patience)
84 its += 1
85 log.debug('Command took %0.6fs (%d cycles a %fs)', time.time() - t_start, its, patience)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070086
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020087 if self._echo:
88 # Skip echo chars
89 rsp = rsp[wlen:]
90 rsp = rsp.strip()
91 rsp = rsp.split(b'\r\n\r\n')
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070092
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020093 log.debug('Got response from modem: %s', rsp)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070094 return rsp
95
Robert Falkenberg18fb82b2021-05-02 10:21:23 +020096 def _check_echo(self):
97 """Verify the correct response to 'AT' command
98 and detect if inputs are echoed by the device
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +070099
Robert Falkenberg18fb82b2021-05-02 10:21:23 +0200100 Although echo of inputs can be enabled/disabled via
101 ATE1/ATE0, respectively, we rather detect the current
102 configuration of the modem without any change.
103 """
104 # Next command shall not strip the echo from the response
105 self._echo = False
106 result = self.send_at_cmd('AT')
107
108 # Verify the response
109 if len(result) > 0:
110 if result[-1] == b'OK':
111 self._echo = False
112 return
113 elif result[-1] == b'AT\r\r\nOK':
114 self._echo = True
115 return
116 raise ReaderError('Interface \'%s\' does not respond to \'AT\' command' % self._device)
117
118 def reset_card(self):
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700119 # Reset the modem, just to be sure
120 if self.send_at_cmd('ATZ') != [b'OK']:
121 raise ReaderError('Failed to reset the modem')
122
123 # Make sure that generic SIM access is supported
124 if self.send_at_cmd('AT+CSIM=?') != [b'OK']:
125 raise ReaderError('The modem does not seem to support SIM access')
126
127 log.info('Modem at \'%s\' is ready!' % self._device)
128
129 def connect(self):
130 pass # Nothing to do really ...
131
132 def disconnect(self):
133 pass # Nothing to do really ...
134
135 def wait_for_card(self, timeout=None, newcardonly=False):
136 pass # Nothing to do really ...
137
Harald Weltec34f9402021-04-10 10:55:24 +0200138 def _send_apdu_raw(self, pdu):
Robert Falkenberg8e15c182021-05-01 08:07:27 +0200139 # Make sure pdu has upper case hex digits [A-F]
140 pdu = pdu.upper()
141
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700142 # Prepare the command as described in 8.17
143 cmd = 'AT+CSIM=%d,\"%s\"' % (len(pdu), pdu)
Robert Falkenberg7cb7c782021-05-06 09:52:31 +0200144 log.debug('Sending command: %s', cmd)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700145
146 # Send AT+CSIM command to the modem
147 # TODO: also handle +CME ERROR: <err>
148 rsp = self.send_at_cmd(cmd)
149 if len(rsp) != 2 or rsp[-1] != b'OK':
150 raise ReaderError('APDU transfer failed: %s' % str(rsp))
151 rsp = rsp[0] # Get rid of b'OK'
152
153 # Make sure that the response has format: b'+CSIM: %d,\"%s\"'
154 try:
155 result = re.match(b'\+CSIM: (\d+),\"([0-9A-F]+)\"', rsp)
156 (rsp_pdu_len, rsp_pdu) = result.groups()
157 except:
158 raise ReaderError('Failed to parse response from modem: %s' % rsp)
159
160 # TODO: make sure we have at least SW
Robert Falkenberge5a5ffb2021-05-06 09:50:43 +0200161 data = rsp_pdu[:-4].decode().lower()
162 sw = rsp_pdu[-4:].decode().lower()
Robert Falkenberg7cb7c782021-05-06 09:52:31 +0200163 log.debug('Command response: %s, %s', data, sw)
Vadim Yanitskiy29ca8042020-05-09 21:23:37 +0700164 return data, sw