Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions device/cheetah/MODEM-CLIENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,14 @@ registration indication), unless `ims_required = yes`.
message appears in the daemon's log.
- **Outgoing SMS** carry a durable 32-hex request id; an interrupted or
uncertain send is marked `unknown`, never repeated automatically.
- **Calls**: a hangup whose release isn't confirmed within 12 s, or a call
left over from a previous run, turns the radio off (best effort, AT+CFUN=0)
and stops sitd with the call still recorded as its own, for an attended
- **Calls**: when a hangup's release isn't confirmed within 12 s, or the
modem refuses an answer or a hang-up, sitd first asks the modem for its
calls (`GET_CURRENT_CALLS`): if it lists none, and no dial is still being
set up, the calls shown here are stale and end here, and sitd keeps
running ("the modem lists no call; N stale call(s) ended here"). Otherwise
(the modem lists a call, the check fails, a dial is pending), and for a call
left over from a previous run, the radio goes off (best effort, AT+CFUN=0)
and sitd stops with the call still recorded as its own, for an attended
reboot. The journal says "Call release not confirmed: <reason>", the radio
and CP states, and "attended reboot required". The RIL no longer stops the
modem unit or powers the CP off: an in-place power-off reset the 9a once,
Expand Down
57 changes: 55 additions & 2 deletions packages/omamobile-modem-sit/lib/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,9 +514,52 @@ def pump(self):
break
self.event(packet)
if self.hangup_deadline and time.monotonic() > self.hangup_deadline:
if self.reconcile('the hangup deadline expired'):
return
self.release_unconfirmed = True
unconfirmed_release(self.client, 'hangup deadline expired')

def reconcile(self, why):
"""Ask the modem before giving a call up as unconfirmed.

A call forwarded straight back to this phone rings here, the
outgoing call ends with cause 17, and the modem never mentions the
incoming one again: it refuses the answer and the hang-up (error 2)
and lists no call. If GET_CURRENT_CALLS is empty, the calls still
shown here are stale and end here; True then. The dial action relies
on the same answer before it dials.

Not while a dial's setup is pending (no status yet, so no modem ID):
the modem may not list a late dial yet, and ending it here would
drop the status of a call that then connects. That case, a modem
that lists a call and a check that fails in any way stay with
unconfirmed_release().
"""
if self.pending or any(call['modem_id'] is None for call in self.live()):
return False
try:
listed = self.client.request(0x0000, timeout=5)
except Exception as error:
# Anything, not only a refusal or a timeout: the transport also
# raises RuntimeError (framing, a short write, the indication
# limit) and EOFError, and none of them may skip the radio-off.
print('Call check after', why, 'failed:', type(error).__name__, flush=True)
return False
if listed != bytes(4):
print('Call check after', why + ': the modem still lists a call', flush=True)
return False
stale = self.live()
for call in stale:
call['state'] = 'terminated'
call['reason'] = 'error'
call['since'] = time.time()
self.hangup_deadline = None
self.audio_stop()
self.save_calls()
print('Call check after', why + ': the modem lists no call;', len(stale), 'stale call(s) ended here',
flush=True)
return True

def send_sms(self, request):
key = request.get('request_id', '')
if not isinstance(key, str) or len(key) != 32 or any(c not in '0123456789abcdef' for c in key):
Expand Down Expand Up @@ -794,12 +837,22 @@ def dispatch(self, request):
try:
# Ordinary voice, audio send/receive, no video.
self.client.request(0x0d02, struct.pack('<HHH', 1, 1, 0))
except ModemError:
if self.reconcile('a refused answer'):
raise RuntimeError('This call has already ended')
self.hangup_deadline = time.monotonic() + 12
raise
except BaseException:
self.hangup_deadline = time.monotonic() + 12
raise
else:
self.hangup_deadline = time.monotonic() + 12
self.client.request(0x0d03, bytes([call['modem_id'], 1, 0]))
try:
self.client.request(0x0d03, bytes([call['modem_id'], 1, 0]))
except ModemError:
if self.reconcile('a refused hang-up'):
return {}
raise
self.pump()
return {}
if action == 'audio':
Expand Down Expand Up @@ -1041,7 +1094,7 @@ def stop(*_):
packet = client.next_indication(.25)
if packet:
service.event(packet)
if service.live():
if service.live() and not service.reconcile('the service stop'):
service.release_unconfirmed = True
unconfirmed_release(client, 'a call release was not confirmed at service stop')
finally:
Expand Down
91 changes: 91 additions & 0 deletions packages/omamobile-modem-sit/test/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,97 @@ def test_unconfirmed_release_turns_radio_off_and_keeps_call_ownership(self):
self.assertEqual(self.service.live(), [call])
self.assertTrue(json.loads((self.root/'active.json').read_text()))

def stale_ring(self):
n=b'+12025550123'; body=struct.pack('<HBH',1,8,len(n))+n
self.service.event(struct.pack('<BBHHH',2,0,0x0d01,8+len(body),0)+body)
return self.service.live()[0]

def test_refused_hangup_of_a_call_the_modem_does_not_list_ends_it_here(self):
call = self.stale_ring()
self.service.audio = MagicMock()
self.client.request.side_effect = [app_service.ModemError(2, b''), bytes(4)]
with patch.object(app_service, 'radio') as radio:
self.assertEqual(self.service.dispatch(dict(action='hangup', id=call['id'])), {})
self.service.pump()
radio.assert_not_called()
self.assertEqual([c.args[0] for c in self.client.request.call_args_list], [0x0d03, 0x0000])
self.assertEqual((call['state'], call['reason']), ('terminated', 'error'))
self.assertIsNone(self.service.hangup_deadline)
self.assertIsNone(self.service.audio)
self.assertFalse(self.service.release_unconfirmed)
self.assertEqual(json.loads((self.root/'active.json').read_text()), [])

def test_refused_answer_of_a_call_the_modem_does_not_list_ends_it_here(self):
call = self.stale_ring()
self.client.request.side_effect = [app_service.ModemError(2, b''), bytes(4)]
with self.assertRaisesRegex(RuntimeError, 'already ended'):
self.service.dispatch(dict(action='accept', id=call['id']))
self.assertEqual(call['state'], 'terminated')
self.assertIsNone(self.service.hangup_deadline)

def test_refused_hangup_of_a_call_the_modem_still_lists_keeps_the_deadline(self):
call = self.stale_ring()
self.client.request.side_effect = [app_service.ModemError(2, b''), struct.pack('<I', 1)]
with self.assertRaises(app_service.ModemError):
self.service.dispatch(dict(action='hangup', id=call['id']))
self.assertEqual(call['state'], 'ringing-in')
self.assertIsNotNone(self.service.hangup_deadline)

def test_call_check_that_fails_keeps_the_deadline(self):
call = self.stale_ring()
self.client.request.side_effect = [app_service.ModemError(2, b''), TimeoutError()]
with self.assertRaises(app_service.ModemError):
self.service.dispatch(dict(action='hangup', id=call['id']))
self.assertEqual(call['state'], 'ringing-in')
self.assertIsNotNone(self.service.hangup_deadline)

def test_call_check_that_breaks_still_ends_in_the_radio_off(self):
# The transport's own errors are not ModemError: the check must not
# let them out past the unconfirmed release.
for error in (RuntimeError('unprocessed indication limit exceeded'), EOFError('SIT channel closed')):
with self.subTest(error=type(error).__name__):
self.service.calls.clear()
self.service.release_unconfirmed = False
call = self.stale_ring()
def request(message, *args, error=error, **kwargs):
if message == 0x0000: raise error
return bytes(4) # the radio state, asked after the radio-off
self.client.request.side_effect = request
self.service.hangup_deadline = 0.001
with patch.object(app_service, 'radio') as radio, \
patch.object(app_service.cp, 'state', return_value=app_service.cp.ONLINE):
with self.assertRaises(app_service.UnconfirmedRelease): self.service.pump()
radio.assert_called_once_with(False)
self.assertTrue(self.service.release_unconfirmed)
self.assertEqual((call['state'], self.service.live()), ('ringing-in', [call]))

def test_pending_dial_is_never_ended_by_the_call_check(self):
# A dial that timed out: still pending, no modem ID, and the modem
# doesn't list it yet. The deadline must not end it here.
self.client.request.side_effect = [bytes(4), TimeoutError()]
with self.assertRaisesRegex(RuntimeError, 'uncertain'):
self.service.dispatch(dict(action='dial', number='+12025550123'))
call = self.service.live()[0]
self.assertEqual(self.service.pending, call['id'])
self.client.request.reset_mock(side_effect=True)
self.client.request.return_value = bytes(4)
self.assertFalse(self.service.reconcile('a test'))
self.client.request.assert_not_called()
self.service.hangup_deadline = 0.001
with patch.object(app_service, 'radio'), \
patch.object(app_service.cp, 'state', return_value=app_service.cp.ONLINE):
with self.assertRaises(app_service.UnconfirmedRelease): self.service.pump()
self.assertTrue(self.service.release_unconfirmed)
self.assertEqual((call['state'], self.service.pending), ('dialing', call['id']))

def test_call_without_a_modem_id_is_never_ended_by_the_call_check(self):
self.stale_ring()
late = self.service.new_call('+12025550123', 'outgoing', 'dialing')
self.client.request.return_value = bytes(4)
self.assertFalse(self.service.reconcile('a test'))
self.client.request.assert_not_called()
self.assertEqual(late['state'], 'dialing')


class RefusedAudioTests(unittest.TestCase):
def test_a_refused_audio_route_does_not_stop_the_call(self):
Expand Down
73 changes: 73 additions & 0 deletions packages/omamobile-modem-sit/test/test_sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,79 @@ def test_unconfirmed_release_at_service_stop_leaves_modem_for_reboot(self):
self.daemon.send_signal(signal.SIGTERM)
self.assert_release_recovery('a call release was not confirmed at service stop', 1)

def forwarded_back_call(self):
"""Dial a number that forwards back here: the dialled call ends and
a call the modem no longer has keeps ringing."""
self.start('--forwarded-back')
self.wait_ready()
self.cli('dial', '+12025550199')
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
calls = json.loads(self.cli('status', '--json'))['calls']
if sorted(c['state'] for c in calls) == ['ringing-in', 'terminated']:
return next(c for c in calls if c['state'] == 'ringing-in')
time.sleep(.1)
self.fail('no stale ringing call: ' + json.dumps(calls))

def assert_stale_call_ended(self, why, request):
calls = json.loads(self.cli('status', '--json'))['calls']
self.assertEqual([c['state'] for c in calls], ['terminated', 'terminated'])
# Longer than the 12 s hangup deadline: sitd is still serving.
time.sleep(13)
self.assertIsNone(self.daemon.poll())
self.assertEqual(json.loads(self.cli('status', '--json'))['modem']['stage'], 'running')
self.assertEqual(json.loads((self.dir / 'run' / 'active.json').read_text()), [])
entries = self.transcript_entries()
self.assertFalse([e for e in entries if 'violation' in e])
self.assertFalse([e for e in entries if e.get('type') == 'at' and e['cmd'] == 'AT+CFUN=0'])
refused = [e for e in entries if e.get('type') == 'resp' and e['id'] == request]
self.assertEqual([e['err'] for e in refused], [2])
log = (self.dir / 'daemon.log').read_text()
self.assertIn(f'Call check after {why}: the modem lists no call; 1 stale call(s) ended here', log)
self.assertNotIn('Call release not confirmed', log)
self.assertNotIn('2025550', log)
self.daemon.send_signal(signal.SIGTERM)
self.assertEqual(self.daemon.wait(15), 0)

def test_refused_hangup_of_a_call_the_modem_no_longer_lists_ends_it_here(self):
self.forwarded_back_call()
self.cli('hangup')
self.assert_stale_call_ended('a refused hang-up', 0x0d03)

def test_refused_answer_of_a_call_the_modem_no_longer_lists_ends_it_here(self):
self.forwarded_back_call()
refused = subprocess.run([sys.executable, str(BIN / 'omamobile-sit'), 'answer'], env=self.env,
capture_output=True, text=True, timeout=60)
self.assertNotEqual(refused.returncode, 0)
self.assertIn('already ended', refused.stderr)
self.assert_stale_call_ended('a refused answer', 0x0d02)

def test_stale_call_at_service_stop_ends_here_and_sitd_exits_cleanly(self):
self.forwarded_back_call()
self.daemon.send_signal(signal.SIGTERM)
self.assertEqual(self.daemon.wait(25), 0)
self.assertEqual(json.loads((self.dir / 'run' / 'active.json').read_text()), [])
log = (self.dir / 'daemon.log').read_text()
self.assertIn('Call check after the service stop: the modem lists no call', log)
self.assertNotIn('Call release not confirmed', log)
at = [e['cmd'] for e in self.transcript_entries() if e.get('type') == 'at']
self.assertNotIn('AT+CFUN=0', at)

def test_pending_dial_the_modem_does_not_list_yet_is_still_unconfirmed(self):
# A dial that timed out is still pending when the deadline expires.
# The modem doesn't list it (yet), but it may still go through, so
# the call isn't ended here: the old path.
self.start('--silent-dial')
self.wait_ready()
uncertain = subprocess.run([sys.executable, str(BIN / 'omamobile-sit'), 'dial', '+12025550199'],
env=self.env, capture_output=True, text=True, timeout=60)
self.assertNotEqual(uncertain.returncode, 0)
self.assertIn('uncertain', uncertain.stderr)
self.assert_release_recovery('hangup deadline expired', 0)
ids = [e['id'] for e in self.transcript_entries() if e.get('type') == 'req']
self.assertEqual(ids.count(0x0000), 1) # the dial's own check only
self.assertNotIn('stale call', (self.dir / 'daemon.log').read_text())

def test_unresolved_previous_call_turns_radio_off_before_exiting(self):
(self.dir / 'run' / 'active.json').write_text('[{}]')
self.start(bringup=False)
Expand Down
2 changes: 1 addition & 1 deletion packages/omamobile-modem-sit/version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.3.41
0.3.43
23 changes: 21 additions & 2 deletions tools/sit-sim
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ fictional 555-01xx ones, addresses are from the documentation ranges.

tools/sit-sim --ipc PATH --router PATH [--transcript FILE] [--search-polls N]
[--incoming-sms] [--no-sim] [--reject-setup CAUSE]
[--no-ims-registration] [--unconfirmed-hangup] [--control PATH]
[--no-ims-registration] [--unconfirmed-hangup] [--forwarded-back]
[--silent-dial] [--control PATH]
[--imsi-plmn MCCMNC] [--no-imsi]

GET_IMSI answers a home network code (--imsi-plmn, default the test
Expand All @@ -33,6 +34,11 @@ network 00101) and a made-up subscriber part; --no-imsi refuses it.
--no-ims-registration accepts ADD_PDN_INFO but never registers IMS (a
carrier whose IMS values differ). --unconfirmed-hangup acknowledges hangup
requests but leaves the call active and never sends a release indication.
--forwarded-back is a dialled number that forwards straight back to this
phone: the dial is accepted, a second call ID rings, the dialled call ends
with cause 17, and the modem never mentions the ringing call again: the call
list is empty, and answering it or hanging it up is refused with error 2.
--silent-dial never answers AIMS_DIAL and lists no call (a late dial).
--control PATH is a datagram socket for tests: "ring" (an incoming IMS call),
"remote-hangup" (the far end ends the current call), "sms" (one text
message), "wap-push" (one MMS notification: an 8-bit SMS to port 2948).
Expand Down Expand Up @@ -287,6 +293,15 @@ class Sim:

def r_0d00(self, mid, token, p): # AIMS_DIAL
call_id = 1
if self.a.silent_dial:
return
if self.a.forwarded_back:
caller = TEST_SENDER.encode()
self.respond(mid, token)
self.after(0.05, lambda: self.call_status(call_id, 2, 31))
self.after(0.1, lambda: self.indicate(0x0d01, struct.pack('<HBH', 1, 2, len(caller)) + caller))
self.after(0.15, lambda: self.call_status(call_id, 6, 17))
return
self.calls[call_id] = 'dialing'
self.respond(mid, token)
self.after(0.05, lambda: self.call_status(call_id, 2))
Expand All @@ -295,14 +310,16 @@ class Sim:
def r_0d03(self, mid, token, p): # AIMS_HANGUP
if self.a.unconfirmed_hangup:
return self.respond(mid, token)
if self.a.forwarded_back and p[0] not in self.calls:
return self.respond(mid, token, 2)
self.calls.pop(p[0], None)
self.respond(mid, token)
self.after(0.05, lambda: self.call_status(p[0], 6, 16))

def r_0d02(self, mid, token, p): # AIMS_ANSWER
ringing = [c for c, state in self.calls.items() if state == 'ringing-in']
if not ringing:
return self.respond(mid, token, 6)
return self.respond(mid, token, 2 if self.a.forwarded_back else 6)
self.calls[ringing[0]] = 'active'
self.respond(mid, token)
self.after(0.05, lambda: self.call_status(ringing[0], 0))
Expand Down Expand Up @@ -368,6 +385,8 @@ def main():
p.add_argument('--reject-setup', type=int, default=0)
p.add_argument('--no-ims-registration', action='store_true')
p.add_argument('--unconfirmed-hangup', action='store_true')
p.add_argument('--forwarded-back', action='store_true')
p.add_argument('--silent-dial', action='store_true')
p.add_argument('--control')
p.add_argument('--imsi-plmn', default='00101')
p.add_argument('--no-imsi', action='store_true')
Expand Down