1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.telephony.satellite.cts;
18 
19 import static android.telephony.satellite.SatelliteManager.SATELLITE_COMMUNICATION_RESTRICTION_REASON_ENTITLEMENT;
20 import static android.telephony.satellite.SatelliteManager.SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION;
21 
22 import static com.android.internal.telephony.satellite.SatelliteController.TIMEOUT_TYPE_DEMO_POINTING_ALIGNED_DURATION_MILLIS;
23 import static com.android.internal.telephony.satellite.SatelliteController.TIMEOUT_TYPE_DEMO_POINTING_NOT_ALIGNED_DURATION_MILLIS;
24 import static com.android.internal.telephony.satellite.SatelliteController.TIMEOUT_TYPE_WAIT_FOR_SATELLITE_ENABLING_RESPONSE;
25 
26 import static com.google.common.truth.Truth.assertThat;
27 
28 import static org.junit.Assert.assertArrayEquals;
29 import static org.junit.Assert.assertEquals;
30 import static org.junit.Assert.assertFalse;
31 import static org.junit.Assert.assertNotEquals;
32 import static org.junit.Assert.assertNotNull;
33 import static org.junit.Assert.assertNull;
34 import static org.junit.Assert.assertTrue;
35 import static org.junit.Assert.fail;
36 import static org.junit.Assume.assumeTrue;
37 
38 import android.Manifest;
39 import android.annotation.FlaggedApi;
40 import android.annotation.NonNull;
41 import android.annotation.Nullable;
42 import android.app.AppOpsManager;
43 import android.app.UiAutomation;
44 import android.bluetooth.BluetoothAdapter;
45 import android.content.BroadcastReceiver;
46 import android.content.Context;
47 import android.content.Intent;
48 import android.content.IntentFilter;
49 import android.content.pm.PackageManager;
50 import android.hardware.radio.RadioError;
51 import android.location.Location;
52 import android.location.LocationManager;
53 import android.location.provider.ProviderProperties;
54 import android.net.ConnectivityManager;
55 import android.net.wifi.WifiManager;
56 import android.nfc.NfcAdapter;
57 import android.os.Build;
58 import android.os.CancellationSignal;
59 import android.os.OutcomeReceiver;
60 import android.os.PersistableBundle;
61 import android.os.Process;
62 import android.os.SystemProperties;
63 import android.platform.test.annotations.RequiresFlagsEnabled;
64 import android.platform.test.flag.junit.CheckFlagsRule;
65 import android.platform.test.flag.junit.DeviceFlagsValueProvider;
66 import android.provider.Settings;
67 import android.telephony.CarrierConfigManager;
68 import android.telephony.SubscriptionManager;
69 import android.telephony.TelephonyManager;
70 import android.telephony.cts.TelephonyManagerTest.ServiceStateRadioStateListener;
71 import android.telephony.satellite.AntennaDirection;
72 import android.telephony.satellite.AntennaPosition;
73 import android.telephony.satellite.NtnSignalStrength;
74 import android.telephony.satellite.PointingInfo;
75 import android.telephony.satellite.SatelliteCapabilities;
76 import android.telephony.satellite.SatelliteDatagram;
77 import android.telephony.satellite.SatelliteManager;
78 import android.telephony.satellite.SatelliteSessionStats;
79 import android.telephony.satellite.stub.NTRadioTechnology;
80 import android.telephony.satellite.stub.SatelliteResult;
81 import android.util.Log;
82 import android.util.Pair;
83 import android.uwb.UwbManager;
84 
85 import androidx.test.InstrumentationRegistry;
86 
87 import com.android.compatibility.common.util.LocationUtils;
88 import com.android.compatibility.common.util.ShellIdentityUtils;
89 import com.android.internal.telephony.flags.Flags;
90 import com.android.internal.telephony.satellite.DatagramController;
91 import com.android.internal.telephony.satellite.SatelliteServiceUtils;
92 
93 import org.junit.After;
94 import org.junit.AfterClass;
95 import org.junit.Before;
96 import org.junit.BeforeClass;
97 import org.junit.Rule;
98 import org.junit.Test;
99 
100 import java.util.ArrayList;
101 import java.util.Arrays;
102 import java.util.HashMap;
103 import java.util.HashSet;
104 import java.util.List;
105 import java.util.Map;
106 import java.util.Set;
107 import java.util.concurrent.CountDownLatch;
108 import java.util.concurrent.LinkedBlockingQueue;
109 import java.util.concurrent.TimeUnit;
110 import java.util.concurrent.atomic.AtomicReference;
111 
112 public class SatelliteManagerTestOnMockService extends SatelliteManagerTestBase {
113     private static final String ALLOW_MOCK_MODEM_PROPERTY = "persist.radio.allow_mock_modem";
114     private static final boolean DEBUG = !"user".equals(Build.TYPE);
115     private static final long TEST_SATELLITE_LISTENING_TIMEOUT_MILLIS = 100;
116     private static final long TEST_SATELLITE_LISTENING_FOREVER_TIMEOUT_MILLIS = 60 * 10 * 1000;
117     private static final long TEST_SATELLITE_DEVICE_ALIGN_TIMEOUT_MILLIS = 100;
118     private static final long TEST_SATELLITE_DEVICE_ALIGN_FOREVER_TIMEOUT_MILLIS = 100000;
119     private static final long TEST_DATAGRAM_DELAY_IN_DEMO_MODE_TIMEOUT_MILLIS = 100;
120     private static final long TEST_DATAGRAM_DELAY_IN_DEMO_MODE_TIMEOUT_LONG_MILLIS = 1000;
121 
122     private static MockSatelliteServiceManager sMockSatelliteServiceManager;
123 
124     /* SatelliteCapabilities constant indicating that the radio technology is proprietary. */
125     private static final Set<Integer> SUPPORTED_RADIO_TECHNOLOGIES;
126     static {
127         SUPPORTED_RADIO_TECHNOLOGIES = new HashSet<>();
128         SUPPORTED_RADIO_TECHNOLOGIES.add(SatelliteManager.NT_RADIO_TECHNOLOGY_PROPRIETARY);
129     }
130 
131     /* SatelliteCapabilities constant indicating that pointing to satellite is required. */
132     private static final boolean POINTING_TO_SATELLITE_REQUIRED = true;
133     /* SatelliteCapabilities constant indicating the maximum number of characters per datagram. */
134     private static final int MAX_BYTES_PER_DATAGRAM = 339;
135     /* SatelliteCapabilites constant antenna position map received from satellite modem. */
136     private static final Map<Integer, AntennaPosition> ANTENNA_POSITION_MAP;
137     static {
138         ANTENNA_POSITION_MAP = new HashMap<>();
ANTENNA_POSITION_MAP.put(SatelliteManager.DISPLAY_MODE_OPENED, new AntennaPosition(new AntennaDirection(1,1,1), SatelliteManager.DEVICE_HOLD_POSITION_PORTRAIT))139         ANTENNA_POSITION_MAP.put(SatelliteManager.DISPLAY_MODE_OPENED,
140                 new AntennaPosition(new AntennaDirection(1,1,1),
141                         SatelliteManager.DEVICE_HOLD_POSITION_PORTRAIT));
ANTENNA_POSITION_MAP.put(SatelliteManager.DISPLAY_MODE_CLOSED, new AntennaPosition(new AntennaDirection(2,2,2), SatelliteManager.DEVICE_HOLD_POSITION_LANDSCAPE_LEFT))142         ANTENNA_POSITION_MAP.put(SatelliteManager.DISPLAY_MODE_CLOSED,
143                 new AntennaPosition(new AntennaDirection(2,2,2),
144                         SatelliteManager.DEVICE_HOLD_POSITION_LANDSCAPE_LEFT));
145     }
146     private static CarrierConfigReceiver sCarrierConfigReceiver;
147 
148     private static final int SUB_ID = SubscriptionManager.DEFAULT_SUBSCRIPTION_ID;
149     private static final String OVERRIDING_COUNTRY_CODES = "US";
150     private static final String SATELLITE_COUNTRY_CODES = "US,UK,CA";
151     private static final String SATELLITE_S2_FILE = "google_us_san_sat_s2.dat";
152     private static final String TEST_PROVIDER = LocationManager.GPS_PROVIDER;
153     private static final float LOCATION_ACCURACY = 95;
154     private static LocationManager sLocationManager;
155 
156     BTWifiNFCStateReceiver mBTWifiNFCSateReceiver = null;
157     UwbAdapterStateCallback mUwbAdapterStateCallback = null;
158     private String mTestSatelliteModeRadios = null;
159     boolean mBTInitState = false;
160     boolean mWifiInitState = false;
161     boolean mNfcInitState = false;
162     boolean mUwbInitState = false;
163 
164 
165     @Rule
166     public final CheckFlagsRule mCheckFlagsRule =
167             DeviceFlagsValueProvider.createCheckFlagsRule();
168 
169     @BeforeClass
beforeAllTests()170     public static void beforeAllTests() throws Exception {
171         logd("beforeAllTests");
172 
173         if (!shouldTestSatelliteWithMockService()) return;
174 
175         beforeAllTestsBase();
176         if (!shouldTestSatellite()) {
177             // FEATURE_TELEPHONY_SATELLITE is missing, so let's set up mock SatelliteManager.
178             sSatelliteManager = new SatelliteManager(getContext());
179         }
180         enforceMockModemDeveloperSetting();
181 
182         grantSatellitePermission();
183 
184         sMockSatelliteServiceManager = new MockSatelliteServiceManager(
185                 InstrumentationRegistry.getInstrumentation());
186         setUpSatelliteAccessAllowed();
187         setupMockSatelliteService();
188 
189         sCarrierConfigReceiver = new CarrierConfigReceiver(SUB_ID);
190         sLocationManager = getContext().getSystemService(LocationManager.class);
191 
192         sMockSatelliteServiceManager.setDatagramControllerBooleanConfig(false,
193                 DatagramController.BOOLEAN_TYPE_WAIT_FOR_DEVICE_ALIGNMENT_IN_DEMO_DATAGRAM, true);
194 
195         revokeSatellitePermission();
196     }
197 
setupMockSatelliteService()198     private static void setupMockSatelliteService() {
199         assertTrue(sMockSatelliteServiceManager.connectSatelliteService());
200 
201         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
202         int count = 0;
203         while (sSatelliteManager.registerForModemStateChanged(
204                 getContext().getMainExecutor(), callback)
205                 != SatelliteManager.SATELLITE_RESULT_SUCCESS
206                 && count < 10) {
207             count++;
208             waitFor(500);
209         }
210         assertTrue(callback.waitUntilResult(1));
211         if (callback.modemState == SatelliteManager.SATELLITE_MODEM_STATE_OFF) {
212             waitFor(2000);
213         } else {
214             assertTrue(callback.waitUntilModemOff(EXTERNAL_DEPENDENT_TIMEOUT));
215         }
216         sSatelliteManager.unregisterForModemStateChanged(callback);
217 
218         assertTrue(isSatelliteSupported());
219         if (!isSatelliteProvisioned()) {
220             logd("Provision satellite");
221 
222             SatelliteProvisionStateCallbackTest satelliteProvisionStateCallback =
223                     new SatelliteProvisionStateCallbackTest();
224             long registerError = sSatelliteManager.registerForProvisionStateChanged(
225                     getContext().getMainExecutor(), satelliteProvisionStateCallback);
226             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerError);
227 
228             assertTrue(provisionSatellite());
229 
230             assertTrue(satelliteProvisionStateCallback.waitUntilResult(1));
231             assertTrue(satelliteProvisionStateCallback.isProvisioned);
232             sSatelliteManager.unregisterForProvisionStateChanged(
233                     satelliteProvisionStateCallback);
234         }
235     }
236 
237     @AfterClass
afterAllTests()238     public static void afterAllTests() {
239         logd("afterAllTests");
240         if (!shouldTestSatelliteWithMockService()) return;
241 
242         grantSatellitePermission();
243 
244         sMockSatelliteServiceManager.setDatagramControllerBooleanConfig(true,
245                 DatagramController.BOOLEAN_TYPE_WAIT_FOR_DEVICE_ALIGNMENT_IN_DEMO_DATAGRAM, false);
246 
247         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
248         long registerResult = sSatelliteManager.registerForModemStateChanged(
249                 getContext().getMainExecutor(), callback);
250         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
251         assertTrue(callback.waitUntilResult(1));
252 
253         assertTrue(sMockSatelliteServiceManager.restoreSatelliteServicePackageName());
254         waitFor(2000);
255         sSatelliteManager.unregisterForModemStateChanged(callback);
256         resetSatelliteAccessControlOverlayConfigs();
257         afterAllTestsBase();
258         sMockSatelliteServiceManager = null;
259         sCarrierConfigReceiver = null;
260         revokeSatellitePermission();
261     }
262 
263     @Before
setUp()264     public void setUp() throws Exception {
265         logd("setUp");
266         if (!shouldTestSatelliteWithMockService()) return;
267         assumeTrue(sMockSatelliteServiceManager != null);
268 
269         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_SUCCESS);
270         sMockSatelliteServiceManager.setWaitToSend(false);
271         sMockSatelliteServiceManager.setShouldRespondTelephony(true);
272         sMockSatelliteServiceManager.mIsPointingUiOverridden = false;
273         assertTrue(sMockSatelliteServiceManager
274                 .setIsSatelliteCommunicationAllowedForCurrentLocationCache("cache_allowed"));
275 
276         // Initialize radio state
277         mBTInitState = false;
278         mWifiInitState = false;
279         mNfcInitState = false;
280         mUwbInitState = false;
281         mTestSatelliteModeRadios = "";
282 
283         SatelliteModeRadiosUpdater satelliteRadiosModeUpdater =
284                 new SatelliteModeRadiosUpdater(getContext());
285         assertTrue(satelliteRadiosModeUpdater.setSatelliteModeRadios(""));
286 
287         grantSatellitePermission();
288         if (!isSatelliteEnabled()) {
289             logd("Enable satellite");
290 
291             SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
292             long registerResult = sSatelliteManager.registerForModemStateChanged(
293                     getContext().getMainExecutor(), callback);
294             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
295             assertTrue(callback.waitUntilResult(1));
296 
297             int i = 0;
298             while (requestSatelliteEnabledWithResult(true, EXTERNAL_DEPENDENT_TIMEOUT)
299                     != SatelliteManager.SATELLITE_RESULT_SUCCESS && i < 3) {
300                 waitFor(500);
301                 i++;
302             }
303 
304             assertTrue(callback.waitUntilResult(1));
305             assertTrue(isSatelliteEnabled());
306             sSatelliteManager.unregisterForModemStateChanged(callback);
307         }
308         revokeSatellitePermission();
309     }
310 
311     @After
tearDown()312     public void tearDown() {
313         logd("tearDown");
314         if (!shouldTestSatelliteWithMockService()) return;
315         assumeTrue(sMockSatelliteServiceManager != null);
316         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_SUCCESS);
317         sMockSatelliteServiceManager.setWaitToSend(false);
318         sMockSatelliteServiceManager.setShouldRespondTelephony(true);
319 
320         grantSatellitePermission();
321         if (isSatelliteEnabled()) {
322             logd("Disable satellite");
323             SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
324             long registerResult = sSatelliteManager.registerForModemStateChanged(
325                     getContext().getMainExecutor(), callback);
326             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
327             assertTrue(callback.waitUntilResult(1));
328 
329             // Disable satellite modem to clean up all pending resources and reset telephony states.
330             requestSatelliteEnabled(false);
331             assertTrue(callback.waitUntilModemOff());
332             assertFalse(isSatelliteEnabled());
333 
334             sSatelliteManager.unregisterForModemStateChanged(callback);
335         }
336         sMockSatelliteServiceManager.restoreSatellitePointingUiClassName();
337         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
338         sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
339         sMockSatelliteServiceManager.clearListeningEnabledList();
340         revokeSatellitePermission();
341         sMockSatelliteServiceManager.mIsPointingUiOverridden = false;
342         assertTrue(sMockSatelliteServiceManager
343                 .setIsSatelliteCommunicationAllowedForCurrentLocationCache(
344                         "cache_clear_and_not_allowed"));
345     }
346 
347     @Test
testProvisionSatelliteService()348     public void testProvisionSatelliteService() {
349         if (!shouldTestSatelliteWithMockService()) return;
350 
351         logd("testProvisionSatelliteService: start");
352         grantSatellitePermission();
353 
354         LinkedBlockingQueue<Integer> error = new LinkedBlockingQueue<>(1);
355         SatelliteProvisionStateCallbackTest satelliteProvisionStateCallback =
356                 new SatelliteProvisionStateCallbackTest();
357         long registerError = sSatelliteManager.registerForProvisionStateChanged(
358                 getContext().getMainExecutor(), satelliteProvisionStateCallback);
359         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerError);
360 
361         if (isSatelliteProvisioned()) {
362             logd("testProvisionSatelliteService: dreprovision");
363             assertTrue(deprovisionSatellite());
364             assertTrue(satelliteProvisionStateCallback.waitUntilResult(1));
365             assertFalse(satelliteProvisionStateCallback.isProvisioned);
366         }
367 
368         logd("testProvisionSatelliteService: provision and cancel");
369         satelliteProvisionStateCallback.clearProvisionedStates();
370         CancellationSignal cancellationSignal = new CancellationSignal();
371         String mText = "This is test provision data.";
372         byte[] testProvisionData = mText.getBytes();
373         sSatelliteManager.provisionService(TOKEN, testProvisionData, cancellationSignal,
374                 getContext().getMainExecutor(), error::offer);
375 
376         Integer errorCode;
377         try {
378             errorCode = error.poll(TIMEOUT, TimeUnit.MILLISECONDS);
379             cancellationSignal.cancel();
380         } catch (InterruptedException ex) {
381             fail("testProvisionSatelliteService: Got InterruptedException ex=" + ex);
382             return;
383         }
384         assertNotNull(errorCode);
385         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, (long) errorCode);
386 
387         // Provision succeeded and then got canceled - deprovisioned
388         assertTrue(satelliteProvisionStateCallback.waitUntilResult(2));
389         assertEquals(2, satelliteProvisionStateCallback.getTotalCountOfProvisionedStates());
390         assertTrue(satelliteProvisionStateCallback.getProvisionedState(0));
391         assertFalse(satelliteProvisionStateCallback.getProvisionedState(1));
392         assertFalse(satelliteProvisionStateCallback.isProvisioned);
393         assertFalse(isSatelliteProvisioned());
394 
395         logd("testProvisionSatelliteService: restore provision state");
396         assertTrue(provisionSatellite());
397         assertTrue(satelliteProvisionStateCallback.waitUntilResult(1));
398         assertTrue(satelliteProvisionStateCallback.isProvisioned);
399         sSatelliteManager.unregisterForProvisionStateChanged(
400                 satelliteProvisionStateCallback);
401 
402         revokeSatellitePermission();
403     }
404 
405     @Test
testProvisioningApiNotSupportedByVendorService()406     public void testProvisioningApiNotSupportedByVendorService() {
407         if (!shouldTestSatelliteWithMockService()) return;
408 
409         logd("testProvisioningApiNotSupportedByVendorService: start");
410         grantSatellitePermission();
411 
412         SatelliteProvisionStateCallbackTest satelliteProvisionStateCallback =
413                 new SatelliteProvisionStateCallbackTest();
414         long registerError = sSatelliteManager.registerForProvisionStateChanged(
415                 getContext().getMainExecutor(), satelliteProvisionStateCallback);
416         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerError);
417 
418         if (isSatelliteProvisioned()) {
419             logd("testProvisioningApiNotSupportedByVendorService: dreprovision");
420             assertTrue(deprovisionSatellite());
421             assertTrue(satelliteProvisionStateCallback.waitUntilResult(1));
422             assertFalse(satelliteProvisionStateCallback.isProvisioned);
423         }
424 
425         sMockSatelliteServiceManager.setProvisioningApiSupported(false);
426 
427         logd("testProvisioningApiNotSupportedByVendorService: provision satellite service");
428         assertTrue(provisionSatellite());
429         assertTrue(satelliteProvisionStateCallback.waitUntilResult(1));
430         assertTrue(satelliteProvisionStateCallback.isProvisioned);
431         assertTrue(isSatelliteProvisioned());
432 
433         logd("testProvisioningApiNotSupportedByVendorService: dreprovision satellite service");
434         assertTrue(deprovisionSatellite());
435         assertTrue(satelliteProvisionStateCallback.waitUntilResult(1));
436         assertFalse(satelliteProvisionStateCallback.isProvisioned);
437         assertFalse(isSatelliteProvisioned());
438 
439         logd("testProvisioningApiNotSupportedByVendorService: restore provision state");
440         sMockSatelliteServiceManager.setProvisioningApiSupported(true);
441         assertTrue(provisionSatellite());
442         assertTrue(satelliteProvisionStateCallback.waitUntilResult(1));
443         assertTrue(satelliteProvisionStateCallback.isProvisioned);
444         assertTrue(isSatelliteProvisioned());
445         sSatelliteManager.unregisterForProvisionStateChanged(
446                 satelliteProvisionStateCallback);
447 
448         revokeSatellitePermission();
449     }
450 
451     @Test
testPointingUICrashHandling()452     public void testPointingUICrashHandling() {
453         if (!shouldTestSatelliteWithMockService()) return;
454 
455         grantSatellitePermission();
456 
457         assertTrue(isSatelliteProvisioned());
458         assertTrue(isSatelliteEnabled());
459 
460         assertTrue(sMockSatelliteServiceManager.overrideExternalSatellitePointingUiClassName());
461         sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
462 
463         // Start Pointing UI app
464         sendSatelliteDatagramSuccess(false, false);
465 
466         // Forcefully stop the Pointing UI app
467         sMockSatelliteServiceManager.clearStopPointingUiActivity();
468         assertTrue(sMockSatelliteServiceManager.stopExternalMockPointingUi());
469         assertTrue(sMockSatelliteServiceManager.waitForEventMockPointingUiActivityStopped(1));
470         sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
471         // Check if the Pointing UI app restarted
472         assertTrue(sMockSatelliteServiceManager.waitForEventMockPointingUiActivityStarted(1));
473 
474         // Kill the Pointing UI app multiple times and check if it is restarted everytime
475         for (int i = 0; i < 10; i++) {
476             sMockSatelliteServiceManager.clearStopPointingUiActivity();
477             // Forcefully stop the Pointing UI app again
478             assertTrue(sMockSatelliteServiceManager.stopExternalMockPointingUi());
479             assertTrue(sMockSatelliteServiceManager.waitForEventMockPointingUiActivityStopped(1));
480             sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
481             // Check if the Pointing UI app has restarted
482             assertTrue(sMockSatelliteServiceManager.waitForEventMockPointingUiActivityStarted(1));
483         }
484         assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
485     }
486 
487     @Test
testSatelliteModemStateChanged()488     public void testSatelliteModemStateChanged() {
489         if (!shouldTestSatelliteWithMockService()) return;
490 
491         grantSatellitePermission();
492 
493         assertTrue(isSatelliteProvisioned());
494 
495         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
496         boolean originalEnabledState = isSatelliteEnabled();
497         boolean registerCallback = false;
498         if (originalEnabledState) {
499             registerCallback = true;
500 
501             long registerResult = sSatelliteManager.registerForModemStateChanged(
502                     getContext().getMainExecutor(), callback);
503             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
504             assertTrue(callback.waitUntilResult(1));
505 
506             requestSatelliteEnabled(false);
507 
508             assertTrue(callback.waitUntilModemOff());
509             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
510             assertFalse(isSatelliteEnabled());
511             callback.clearModemStates();
512         }
513         if (!registerCallback) {
514             long registerResult = sSatelliteManager
515                     .registerForModemStateChanged(getContext().getMainExecutor(),
516                             callback);
517             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
518             assertTrue(callback.waitUntilResult(1));
519             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
520         }
521 
522         assertTrue(sMockSatelliteServiceManager.connectSatelliteGatewayService());
523         assertTrue(sMockSatelliteServiceManager.overrideSatellitePointingUiClassName());
524         sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
525         requestSatelliteEnabled(true);
526 
527         assertTrue(callback.waitUntilResult(2));
528         assertEquals(2, callback.getTotalCountOfModemStates());
529         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
530                 callback.getModemState(0));
531         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.getModemState(1));
532         assertTrue(isSatelliteEnabled());
533         assertTrue(sMockSatelliteServiceManager.waitForRemoteSatelliteGatewayServiceConnected(1));
534         assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
535 
536         SatelliteModemStateCallbackTest
537                 callback1 = new SatelliteModemStateCallbackTest();
538         long registerResult = sSatelliteManager
539                 .registerForModemStateChanged(getContext().getMainExecutor(), callback1);
540         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
541         assertTrue(callback1.waitUntilResult(1));
542         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback1.modemState);
543         sSatelliteManager.unregisterForModemStateChanged(callback);
544 
545         assertTrue(sMockSatelliteServiceManager.setSatelliteListeningTimeoutDuration(
546                 TEST_SATELLITE_LISTENING_TIMEOUT_MILLIS));
547 
548         // Verify state transitions: IDLE -> TRANSFERRING -> LISTENING -> IDLE
549         sendSatelliteDatagramWithSuccessfulResult(callback1, true);
550 
551         assertTrue(sMockSatelliteServiceManager.setSatelliteListeningTimeoutDuration(
552                 TEST_SATELLITE_LISTENING_FOREVER_TIMEOUT_MILLIS));
553 
554         // Move to LISTENING state
555         sendSatelliteDatagramWithSuccessfulResult(callback1, false);
556 
557         // Verify state transitions: LISTENING -> TRANSFERRING -> LISTENING
558         receiveSatelliteDatagramWithSuccessfulResult(callback1);
559 
560         // Verify state transitions: LISTENING -> TRANSFERRING -> IDLE
561         sendSatelliteDatagramWithFailedResult(callback1);
562 
563         // Move to LISTENING state
564         sendSatelliteDatagramWithSuccessfulResult(callback1, false);
565 
566         // Verify state transitions: LISTENING -> TRANSFERRING -> IDLE
567         receiveSatelliteDatagramWithFailedResult(callback1);
568 
569         callback1.clearModemStates();
570         requestSatelliteEnabled(false);
571         assertTrue(callback1.waitUntilModemOff());
572         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback1.modemState);
573         assertFalse(isSatelliteEnabled());
574         assertTrue(
575                 sMockSatelliteServiceManager.waitForRemoteSatelliteGatewayServiceDisconnected(1));
576 
577         sSatelliteManager.unregisterForModemStateChanged(callback1);
578         assertTrue(sMockSatelliteServiceManager.setSatelliteListeningTimeoutDuration(0));
579         assertTrue(sMockSatelliteServiceManager.restoreSatelliteGatewayServicePackageName());
580 
581         revokeSatellitePermission();
582     }
583 
584     @Test
testSatelliteModemStateChangedForNbIot()585     public void testSatelliteModemStateChangedForNbIot() {
586         if (!shouldTestSatelliteWithMockService() || !Flags.oemEnabledSatelliteFlag()) return;
587 
588         updateSupportedRadioTechnologies(new int[]{NTRadioTechnology.NB_IOT_NTN}, true);
589 
590         grantSatellitePermission();
591         assertTrue(isSatelliteProvisioned());
592 
593         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
594         boolean originalEnabledState = isSatelliteEnabled();
595         boolean registerCallback = false;
596         if (originalEnabledState) {
597             registerCallback = true;
598 
599             long registerResult = sSatelliteManager.registerForModemStateChanged(
600                     getContext().getMainExecutor(), callback);
601             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
602             assertTrue(callback.waitUntilResult(1));
603 
604             requestSatelliteEnabled(false);
605 
606             assertTrue(callback.waitUntilModemOff());
607             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
608             assertFalse(isSatelliteEnabled());
609             callback.clearModemStates();
610         }
611         if (!registerCallback) {
612             long registerResult = sSatelliteManager
613                     .registerForModemStateChanged(getContext().getMainExecutor(),
614                             callback);
615             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
616             assertTrue(callback.waitUntilResult(1));
617             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
618         }
619 
620         assertTrue(sMockSatelliteServiceManager.connectSatelliteGatewayService());
621         assertTrue(sMockSatelliteServiceManager.overrideSatellitePointingUiClassName());
622         sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
623         requestSatelliteEnabled(true);
624         assertTrue(callback.waitUntilResult(2));
625         assertEquals(2, callback.getTotalCountOfModemStates());
626         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
627                 callback.getModemState(0));
628         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED,
629                 callback.getModemState(1));
630         assertTrue(isSatelliteEnabled());
631         assertTrue(sMockSatelliteServiceManager.waitForRemoteSatelliteGatewayServiceConnected(1));
632         assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
633 
634         callback.clearModemStates();
635         requestSatelliteEnabled(false);
636         assertTrue(callback.waitUntilResult(2));
637         assertEquals(2, callback.getTotalCountOfModemStates());
638         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DISABLING_SATELLITE,
639                 callback.getModemState(0));
640         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.getModemState(1));
641         assertFalse(isSatelliteEnabled());
642 
643         assertTrue(sMockSatelliteServiceManager.setSatelliteListeningTimeoutDuration(
644                 TEST_SATELLITE_LISTENING_TIMEOUT_MILLIS));
645 
646         // Verify state transitions: OFF -> ENABLING_SATELLITE -> NOT_CONNECTED -> IDLE
647         callback.clearModemStates();
648         requestSatelliteEnabled(true);
649         assertTrue(callback.waitUntilResult(3));
650         assertTrue(isSatelliteEnabled());
651         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
652                 callback.getModemState(0));
653         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED,
654                 callback.getModemState(1));
655         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE,
656                 callback.getModemState(2));
657 
658         callback.clearModemStates();
659         requestSatelliteEnabled(false);
660         assertTrue(callback.waitUntilResult(2));
661         assertEquals(2, callback.getTotalCountOfModemStates());
662         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DISABLING_SATELLITE,
663                 callback.getModemState(0));
664         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.getModemState(1));
665         assertFalse(isSatelliteEnabled());
666 
667         assertTrue(sMockSatelliteServiceManager.setSatelliteListeningTimeoutDuration(
668                 TEST_SATELLITE_LISTENING_FOREVER_TIMEOUT_MILLIS));
669 
670         callback.clearModemStates();
671         requestSatelliteEnabled(true);
672         assertTrue(callback.waitUntilResult(2));
673         assertEquals(2, callback.getTotalCountOfModemStates());
674         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
675                 callback.getModemState(0));
676         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED,
677                 callback.getModemState(1));
678         assertTrue(isSatelliteEnabled());
679 
680         assertTrue(sMockSatelliteServiceManager.setSatelliteListeningTimeoutDuration(
681                 TEST_SATELLITE_LISTENING_TIMEOUT_MILLIS));
682 
683         // Verify state transitions when sending: NOT_CONNECTED -> CONNECTED -> TRANSFERRING
684         // -> CONNECTED -> IDLE
685         sMockSatelliteServiceManager.clearListeningEnabledList();
686         callback.clearModemStates();
687         sendDatagramWithoutResponse();
688         verifyNbIotStateTransitionsWithSendingOnConnected(callback, true);
689 
690         // Verify state transitions when receiving: IDLE -> NOT_CONNECTED -> CONNECTED
691         // -> TRANSFERRING -> CONNECTED -> IDLE
692         verifyNbIotStateTransitionsWithReceivingOnIdle(callback, true);
693 
694         // Verify not state transition on IDLE state
695         verifyNbIotStateTransitionsWithTransferringFailureOnIdle(callback);
696 
697         // Verify state transition: IDLE -> NOT_CONNECTED -> POWER_OFF
698         verifyNbIotStateTransitionsWithSendingAborted(callback);
699 
700         // Verify state transitions: POWER_OFF -> NOT_CONNECTED
701         callback.clearModemStates();
702         requestSatelliteEnabled(true);
703         assertTrue(callback.waitUntilResult(2));
704         assertEquals(2, callback.getTotalCountOfModemStates());
705         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
706                 callback.getModemState(0));
707         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED,
708                 callback.getModemState(1));
709         assertTrue(isSatelliteEnabled());
710 
711         assertTrue(sMockSatelliteServiceManager.setSatelliteListeningTimeoutDuration(
712                 TEST_SATELLITE_LISTENING_FOREVER_TIMEOUT_MILLIS));
713 
714         // Verify state transitions when sending: NOT_CONNECTED -> CONNECTED -> TRANSFERRING
715         // -> CONNECTED
716         sMockSatelliteServiceManager.clearListeningEnabledList();
717         callback.clearModemStates();
718         sendDatagramWithoutResponse();
719         verifyNbIotStateTransitionsWithSendingOnConnected(callback, false);
720 
721         // Verify state transitions: CONNECTED -> POWER_OFF
722         callback.clearModemStates();
723         requestSatelliteEnabled(false);
724         assertTrue(callback.waitUntilResult(2));
725         assertEquals(2, callback.getTotalCountOfModemStates());
726         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DISABLING_SATELLITE,
727                 callback.getModemState(0));
728         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.getModemState(1));
729         assertFalse(isSatelliteEnabled());
730         assertTrue(
731                 sMockSatelliteServiceManager.waitForRemoteSatelliteGatewayServiceDisconnected(1));
732 
733         // Verify state transitions: POWER_OFF -> NOT_CONNECTED
734         callback.clearModemStates();
735         requestSatelliteEnabled(true);
736         assertTrue(callback.waitUntilResult(2));
737         assertEquals(2, callback.getTotalCountOfModemStates());
738         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
739                 callback.getModemState(0));
740         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED,
741                 callback.getModemState(1));
742         assertTrue(isSatelliteEnabled());
743 
744         // Move to CONNECTED state
745         callback.clearModemStates();
746         sMockSatelliteServiceManager.sendOnSatelliteModemStateChanged(
747                 SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED);
748         assertTrue(callback.waitUntilResult(1));
749         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED, callback.modemState);
750 
751         // Verify state transitions: CONNECTED -> TRANSFERRING -> CONNECTED
752         verifyNbIotStateTransitionsWithReceivingOnConnected(callback);
753 
754         sSatelliteManager.unregisterForModemStateChanged(callback);
755         assertTrue(sMockSatelliteServiceManager.setSatelliteListeningTimeoutDuration(0));
756         assertTrue(sMockSatelliteServiceManager.restoreSatelliteGatewayServicePackageName());
757         updateSupportedRadioTechnologies(new int[]{NTRadioTechnology.PROPRIETARY}, false);
758 
759         revokeSatellitePermission();
760     }
761 
762     @Test
testSendKeepAliveDatagramInNotConnectedState()763     public void testSendKeepAliveDatagramInNotConnectedState() {
764         if (!shouldTestSatelliteWithMockService() || !Flags.oemEnabledSatelliteFlag()) return;
765 
766         updateSupportedRadioTechnologies(new int[]{NTRadioTechnology.NB_IOT_NTN}, true);
767 
768         grantSatellitePermission();
769         assertTrue(isSatelliteProvisioned());
770 
771         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
772         boolean originalEnabledState = isSatelliteEnabled();
773         boolean registerCallback = false;
774         if (originalEnabledState) {
775             registerCallback = true;
776 
777             long registerResult = sSatelliteManager.registerForModemStateChanged(
778                     getContext().getMainExecutor(), callback);
779             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
780             assertTrue(callback.waitUntilResult(1));
781 
782             requestSatelliteEnabled(false);
783 
784             assertTrue(callback.waitUntilModemOff());
785             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
786             assertFalse(isSatelliteEnabled());
787             callback.clearModemStates();
788         }
789         if (!registerCallback) {
790             long registerResult = sSatelliteManager
791                     .registerForModemStateChanged(getContext().getMainExecutor(),
792                             callback);
793             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
794             assertTrue(callback.waitUntilResult(1));
795             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
796         }
797 
798         assertTrue(sMockSatelliteServiceManager.connectSatelliteGatewayService());
799         assertTrue(sMockSatelliteServiceManager.overrideSatellitePointingUiClassName());
800         sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
801         requestSatelliteEnabled(true);
802         assertTrue(callback.waitUntilResult(2));
803         assertEquals(2, callback.getTotalCountOfModemStates());
804         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
805                 callback.getModemState(0));
806         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED,
807                 callback.getModemState(1));
808         assertTrue(isSatelliteEnabled());
809         assertTrue(sMockSatelliteServiceManager.waitForRemoteSatelliteGatewayServiceConnected(1));
810         assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
811 
812         SatelliteTransmissionUpdateCallbackTest datagramCallback = startTransmissionUpdates();
813         String mText = "This is a test datagram message from user";
814         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
815         LinkedBlockingQueue<Integer> sosResultListener = new LinkedBlockingQueue<>(1);
816         LinkedBlockingQueue<Integer> keepAliveResultListener = new LinkedBlockingQueue<>(1);
817         sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
818         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
819 
820         // Send SOS satellite datagram
821         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
822                 datagram, true, getContext().getMainExecutor(),
823                 sosResultListener::offer);
824 
825         // Expected datagram transfer state transitions: IDLE -> WAITING_FOR_CONNECTED
826         assertTrue(datagramCallback.waitUntilOnSendDatagramStateChanged(1));
827         assertThat(datagramCallback.getNumOfSendDatagramStateChanges()).isEqualTo(1);
828         assertThat(datagramCallback.getSendDatagramStateChange(0)).isEqualTo(
829                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
830                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_WAITING_TO_CONNECT,
831                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
832 
833         // Send keepAlive satellite datagram
834         datagramCallback.clearSendDatagramStateChanges();
835         callback.clearModemStates();
836         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_KEEP_ALIVE,
837                 datagram, true, getContext().getMainExecutor(),
838                 keepAliveResultListener::offer);
839 
840         // Modem state and datagram transfer state should not be updated
841         assertFalse(datagramCallback.waitUntilOnSendDatagramStateChanged(1));
842         assertFalse(callback.waitUntilResult(1));
843 
844         Integer errorCode;
845         try {
846             errorCode = keepAliveResultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
847         } catch (InterruptedException ex) {
848             fail("testSendSatelliteDatagram_success: Got InterruptedException in waiting"
849                     + " for the sendDatagram result code");
850             return;
851         }
852         assertNotNull(errorCode);
853         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
854         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
855 
856         // Move satellite to CONNECTED state
857         sMockSatelliteServiceManager.sendOnSatelliteModemStateChanged(
858                 SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED);
859 
860         // The SOS datagram should be sent
861         int expectedNumberOfEvents = 3;
862         assertTrue(callback.waitUntilResult(expectedNumberOfEvents));
863         assertEquals(expectedNumberOfEvents, callback.getTotalCountOfModemStates());
864         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED,
865                 callback.getModemState(0));
866         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DATAGRAM_TRANSFERRING,
867                 callback.getModemState(1));
868         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED,
869                 callback.getModemState(2));
870 
871         // Expected datagram transfer state transitions: WAITING_FOR_CONNECTED -> SENDING
872         // -> SEND_SUCCESS -> IDLE
873         assertTrue(datagramCallback.waitUntilOnSendDatagramStateChanged(3));
874         assertThat(datagramCallback.getNumOfSendDatagramStateChanges()).isEqualTo(3);
875         assertThat(datagramCallback.getSendDatagramStateChange(0)).isEqualTo(
876                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
877                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
878                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
879         assertThat(datagramCallback.getSendDatagramStateChange(1)).isEqualTo(
880                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
881                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
882                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
883         assertThat(datagramCallback.getSendDatagramStateChange(2)).isEqualTo(
884                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
885                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
886                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
887 
888         sSatelliteManager.stopTransmissionUpdates(datagramCallback, getContext().getMainExecutor(),
889                 keepAliveResultListener::offer);
890         sSatelliteManager.unregisterForModemStateChanged(callback);
891         assertTrue(sMockSatelliteServiceManager.setSatelliteListeningTimeoutDuration(0));
892         assertTrue(sMockSatelliteServiceManager.restoreSatelliteGatewayServicePackageName());
893         updateSupportedRadioTechnologies(new int[]{NTRadioTechnology.PROPRIETARY}, false);
894 
895         revokeSatellitePermission();
896     }
897 
sendDatagramWithoutResponse()898     private void sendDatagramWithoutResponse() {
899         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
900                 startTransmissionUpdates();
901 
902         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
903         String mText = "This is a test datagram message from user";
904         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
905 
906         sSatelliteManager.sendDatagram(
907                 SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE, datagram, true,
908                 getContext().getMainExecutor(), resultListener::offer);
909 
910         Integer errorCode;
911         try {
912             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
913         } catch (InterruptedException ex) {
914             fail("sendDatagramWithoutResponse: Got InterruptedException in waiting"
915                     + " for the sendDatagram result code, ex=" + ex);
916             return;
917         }
918         assertNull(errorCode);
919 
920         // Expected datagram transfer state transitions: IDLE -> WAITING_FOR_CONNECTED
921         assertTrue(transmissionUpdateCallback.waitUntilOnSendDatagramStateChanged(1));
922         assertThat(transmissionUpdateCallback.getNumOfSendDatagramStateChanges()).isEqualTo(1);
923         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(0)).isEqualTo(
924                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
925                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_WAITING_TO_CONNECT,
926                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
927 
928         stopTransmissionUpdates(transmissionUpdateCallback);
929     }
930 
verifyNbIotStateTransitionsWithSendingOnConnected( @onNull SatelliteModemStateCallbackTest callback, boolean moveToIdleState)931     private void verifyNbIotStateTransitionsWithSendingOnConnected(
932             @NonNull SatelliteModemStateCallbackTest callback, boolean moveToIdleState) {
933         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED, callback.modemState);
934         callback.clearModemStates();
935 
936         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
937                 startTransmissionUpdates();
938 
939         // Move satellite to CONNECTED state
940         sMockSatelliteServiceManager.sendOnSatelliteModemStateChanged(
941                 SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED);
942 
943         int expectedNumberOfEvents = moveToIdleState ? 4 : 3;
944         assertTrue(callback.waitUntilResult(expectedNumberOfEvents));
945         assertEquals(expectedNumberOfEvents, callback.getTotalCountOfModemStates());
946         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED,
947                 callback.getModemState(0));
948         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DATAGRAM_TRANSFERRING,
949                 callback.getModemState(1));
950         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED,
951                 callback.getModemState(2));
952         if (moveToIdleState) {
953             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE,
954                     callback.getModemState(3));
955         }
956 
957         // Expected datagram transfer state transitions: WAITING_FOR_CONNECTED -> SENDING
958         // -> SEND_SUCCESS -> IDLE
959         assertTrue(transmissionUpdateCallback.waitUntilOnSendDatagramStateChanged(3));
960         assertThat(transmissionUpdateCallback.getNumOfSendDatagramStateChanges()).isEqualTo(3);
961         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(0)).isEqualTo(
962                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
963                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
964                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
965         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(1)).isEqualTo(
966                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
967                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
968                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
969         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(2)).isEqualTo(
970                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
971                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
972                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
973 
974         stopTransmissionUpdates(transmissionUpdateCallback);
975     }
976 
verifyNbIotStateTransitionsWithTransferringFailureOnIdle( @onNull SatelliteModemStateCallbackTest callback)977     private void verifyNbIotStateTransitionsWithTransferringFailureOnIdle(
978             @NonNull SatelliteModemStateCallbackTest callback) {
979         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.modemState);
980 
981         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
982                 startTransmissionUpdates();
983 
984         // Test sending failure
985         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
986         String mText = "This is a test datagram message from user";
987         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
988 
989         callback.clearModemStates();
990         sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(false,
991                 DatagramController.TIMEOUT_TYPE_DATAGRAM_WAIT_FOR_CONNECTED_STATE, 1000);
992         // Return failure for the request to disable cellular scanning when exiting IDLE state.
993         sMockSatelliteServiceManager.setEnableCellularScanningErrorCode(
994                 SatelliteManager.SATELLITE_RESULT_SERVICE_ERROR);
995         sSatelliteManager.sendDatagram(
996                 SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE, datagram, true,
997                 getContext().getMainExecutor(), resultListener::offer);
998 
999         assertFalse(callback.waitUntilResult(1));
1000         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.modemState);
1001 
1002         // Expected datagram transfer state transitions: IDLE -> WAITING_FOR_CONNECTED -> FAILED
1003         // -> IDLE.
1004         assertTrue(transmissionUpdateCallback.waitUntilOnSendDatagramStateChanged(3));
1005         assertThat(transmissionUpdateCallback.getNumOfSendDatagramStateChanges()).isEqualTo(3);
1006         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(0)).isEqualTo(
1007                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1008                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_WAITING_TO_CONNECT,
1009                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1010         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(1)).isEqualTo(
1011                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1012                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
1013                         1, SatelliteManager.SATELLITE_RESULT_NOT_REACHABLE));
1014         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(2)).isEqualTo(
1015                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1016                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
1017                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1018 
1019         // Datagram wait for connected state timer should have timed out and the send request should
1020         // have been aborted.
1021         Integer errorCode;
1022         try {
1023             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1024         } catch (InterruptedException ex) {
1025             fail("verifyNbIotStateTransitionsWithTransferringFailureOnIdle: Got "
1026                     + "InterruptedException in waiting for the sendDatagram result code"
1027                     + ", ex=" + ex);
1028             return;
1029         }
1030         assertNotNull(errorCode);
1031         assertEquals(SatelliteManager.SATELLITE_RESULT_NOT_REACHABLE, (long) errorCode);
1032 
1033         // Test receiving failure
1034         resultListener.clear();
1035         sMockSatelliteServiceManager.setEnableCellularScanningErrorCode(
1036                 SatelliteResult.SATELLITE_RESULT_ERROR);
1037         callback.clearModemStates();
1038         sSatelliteManager.pollPendingDatagrams(getContext().getMainExecutor(),
1039                 resultListener::offer);
1040 
1041         assertFalse(callback.waitUntilResult(1));
1042         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.modemState);
1043 
1044         assertTrue(transmissionUpdateCallback
1045                 .waitUntilOnReceiveDatagramStateChanged(3));
1046         assertThat(transmissionUpdateCallback.getNumOfReceiveDatagramStateChanges())
1047                 .isEqualTo(3);
1048         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
1049                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1050                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_WAITING_TO_CONNECT,
1051                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1052         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(1)).isEqualTo(
1053                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1054                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_FAILED,
1055                         0, SatelliteManager.SATELLITE_RESULT_NOT_REACHABLE));
1056         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(2)).isEqualTo(
1057                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1058                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
1059                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1060 
1061         // Datagram wait for connected state timer should have timed out and the poll request should
1062         // have been aborted.
1063         try {
1064             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1065         } catch (InterruptedException ex) {
1066             fail("verifyNbIotStateTransitionsWithTransferringFailureOnIdle: Got "
1067                     + "InterruptedException in waiting for the pollPendingDatagrams result"
1068                     + " code, ex=" + ex);
1069             return;
1070         }
1071         assertNotNull(errorCode);
1072         assertEquals(SatelliteManager.SATELLITE_RESULT_NOT_REACHABLE, (long) errorCode);
1073 
1074         sMockSatelliteServiceManager.setEnableCellularScanningErrorCode(
1075                 SatelliteManager.SATELLITE_RESULT_SUCCESS);
1076         sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(true,
1077                 DatagramController.TIMEOUT_TYPE_DATAGRAM_WAIT_FOR_CONNECTED_STATE, 0);
1078         stopTransmissionUpdates(transmissionUpdateCallback);
1079     }
1080 
verifyNbIotStateTransitionsWithSendingAborted( @onNull SatelliteModemStateCallbackTest callback)1081     private void verifyNbIotStateTransitionsWithSendingAborted(
1082             @NonNull SatelliteModemStateCallbackTest callback) {
1083         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.modemState);
1084 
1085         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
1086                 startTransmissionUpdates();
1087 
1088         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
1089         String mText = "This is a test datagram message from user";
1090         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
1091 
1092         callback.clearModemStates();
1093         sSatelliteManager.sendDatagram(
1094                 SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE, datagram, true,
1095                 getContext().getMainExecutor(), resultListener::offer);
1096 
1097         Integer errorCode;
1098         try {
1099             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1100         } catch (InterruptedException ex) {
1101             fail("verifyNbIotStateTransitionsWithSendingAborted: Got InterruptedException"
1102                     + " in waiting for the sendDatagram result code, ex=" + ex);
1103             return;
1104         }
1105         assertNull(errorCode);
1106 
1107         assertTrue(callback.waitUntilResult(1));
1108         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED, callback.modemState);
1109 
1110         // Turn off satellite modem. The send request should be aborted.
1111         callback.clearModemStates();
1112         sMockSatelliteServiceManager.sendOnSatelliteModemStateChanged(
1113                 SatelliteManager.SATELLITE_MODEM_STATE_OFF);
1114 
1115         try {
1116             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1117         } catch (InterruptedException ex) {
1118             fail("verifyNbIotStateTransitionsWithSendingAborted: Got InterruptedException"
1119                     + " in waiting for the sendDatagram result code, ex=" + ex);
1120             return;
1121         }
1122         assertNotNull(errorCode);
1123         assertEquals(SatelliteManager.SATELLITE_RESULT_REQUEST_ABORTED, (long) errorCode);
1124 
1125         // Expected datagram transfer state transitions: IDLE -> WAITING_FOR_CONNECTED -> FAILED
1126         // -> IDLE.
1127         assertTrue(transmissionUpdateCallback.waitUntilOnSendDatagramStateChanged(3));
1128         assertThat(transmissionUpdateCallback.getNumOfSendDatagramStateChanges()).isEqualTo(3);
1129         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(0)).isEqualTo(
1130                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1131                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_WAITING_TO_CONNECT,
1132                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1133         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(1)).isEqualTo(
1134                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1135                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
1136                         1, SatelliteManager.SATELLITE_RESULT_REQUEST_ABORTED));
1137         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(2)).isEqualTo(
1138                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1139                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
1140                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1141 
1142         assertTrue(callback.waitUntilResult(1));
1143         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
1144         stopTransmissionUpdates(transmissionUpdateCallback);
1145     }
1146 
verifyNbIotStateTransitionsWithReceivingOnIdle( @onNull SatelliteModemStateCallbackTest callback, boolean moveToIdleState)1147     private void verifyNbIotStateTransitionsWithReceivingOnIdle(
1148             @NonNull SatelliteModemStateCallbackTest callback, boolean moveToIdleState) {
1149         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.modemState);
1150 
1151         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
1152                 startTransmissionUpdates();
1153 
1154         // Verify state transitions: IDLE -> NOT_CONNECTED
1155         callback.clearModemStates();
1156         sMockSatelliteServiceManager.clearPollPendingDatagramPermits();
1157         sMockSatelliteServiceManager.sendOnPendingDatagrams();
1158         assertFalse(sMockSatelliteServiceManager.waitForEventOnPollPendingSatelliteDatagrams(1));
1159         assertTrue(callback.waitUntilResult(1));
1160         assertEquals(1, callback.getTotalCountOfModemStates());
1161         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED, callback.modemState);
1162         // Expected datagram transfer state transitions: IDLE -> WAITING_FOR_CONNECTED
1163         assertTrue(transmissionUpdateCallback
1164                 .waitUntilOnReceiveDatagramStateChanged(1));
1165         assertThat(transmissionUpdateCallback.getNumOfReceiveDatagramStateChanges())
1166                 .isEqualTo(1);
1167         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
1168                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1169                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_WAITING_TO_CONNECT,
1170                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1171 
1172         // Verify state transitions: NOT_CONNECTED -> CONNECTED -> TRANSFERRING
1173         callback.clearModemStates();
1174         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
1175         sMockSatelliteServiceManager.sendOnSatelliteModemStateChanged(
1176                 SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED);
1177         assertTrue(callback.waitUntilResult(2));
1178         assertEquals(2, callback.getTotalCountOfModemStates());
1179         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED,
1180                 callback.getModemState(0));
1181         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DATAGRAM_TRANSFERRING,
1182                 callback.getModemState(1));
1183         // Telephony should send the request pollPendingDatagrams to modem
1184         assertTrue(sMockSatelliteServiceManager.waitForEventOnPollPendingSatelliteDatagrams(1));
1185 
1186         // Expected datagram transfer state transitions: WAITING_FOR_CONNECTED -> RECEIVING
1187         assertTrue(transmissionUpdateCallback
1188                 .waitUntilOnReceiveDatagramStateChanged(1));
1189         assertThat(transmissionUpdateCallback.getNumOfReceiveDatagramStateChanges())
1190                 .isEqualTo(1);
1191         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
1192                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1193                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVING,
1194                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1195 
1196         verifyNbIotStateTransitionsWithDatagramReceivedOnTransferring(
1197                 callback, moveToIdleState, transmissionUpdateCallback);
1198         stopTransmissionUpdates(transmissionUpdateCallback);
1199     }
1200 
verifyNbIotStateTransitionsWithDatagramReceivedOnTransferring( @onNull SatelliteModemStateCallbackTest callback, boolean moveToIdleState, SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback)1201     private void verifyNbIotStateTransitionsWithDatagramReceivedOnTransferring(
1202             @NonNull SatelliteModemStateCallbackTest callback, boolean moveToIdleState,
1203             SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback) {
1204         assertEquals(
1205                 SatelliteManager.SATELLITE_MODEM_STATE_DATAGRAM_TRANSFERRING, callback.modemState);
1206 
1207         SatelliteDatagramCallbackTest satelliteDatagramCallback =
1208                 new SatelliteDatagramCallbackTest();
1209         sSatelliteManager.registerForIncomingDatagram(
1210                 getContext().getMainExecutor(), satelliteDatagramCallback);
1211 
1212         String receivedText = "This is a test datagram message from satellite";
1213         android.telephony.satellite.stub.SatelliteDatagram receivedDatagram =
1214                 new android.telephony.satellite.stub.SatelliteDatagram();
1215         receivedDatagram.data = receivedText.getBytes();
1216 
1217         callback.clearModemStates();
1218         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
1219         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 0);
1220 
1221         assertTrue(satelliteDatagramCallback.waitUntilResult(1));
1222         assertArrayEquals(satelliteDatagramCallback.mDatagram.getSatelliteDatagram(),
1223                 receivedText.getBytes());
1224 
1225         int expectedNumberOfEvents = moveToIdleState ? 2 : 1;
1226         assertTrue(callback.waitUntilResult(expectedNumberOfEvents));
1227         assertEquals(expectedNumberOfEvents, callback.getTotalCountOfModemStates());
1228         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED,
1229                 callback.getModemState(0));
1230         if (moveToIdleState) {
1231             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE,
1232                     callback.getModemState(1));
1233         }
1234 
1235         // Expected datagram transfer state transitions: RECEIVING -> RECEIVE_SUCCESS -> IDLE
1236         assertTrue(transmissionUpdateCallback
1237                 .waitUntilOnReceiveDatagramStateChanged(2));
1238         assertThat(transmissionUpdateCallback.getNumOfReceiveDatagramStateChanges())
1239                 .isEqualTo(2);
1240         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
1241                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1242                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_SUCCESS,
1243                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1244         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(1)).isEqualTo(
1245                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1246                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
1247                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1248 
1249         sSatelliteManager.unregisterForIncomingDatagram(satelliteDatagramCallback);
1250     }
1251 
verifyNbIotStateTransitionsWithReceivingOnConnected( @onNull SatelliteModemStateCallbackTest callback)1252     private void verifyNbIotStateTransitionsWithReceivingOnConnected(
1253             @NonNull SatelliteModemStateCallbackTest callback) {
1254         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED, callback.modemState);
1255 
1256         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
1257                 startTransmissionUpdates();
1258 
1259         SatelliteDatagramCallbackTest satelliteDatagramCallback =
1260                 new SatelliteDatagramCallbackTest();
1261         sSatelliteManager.registerForIncomingDatagram(
1262                 getContext().getMainExecutor(), satelliteDatagramCallback);
1263 
1264         String receivedText = "This is a test datagram message from satellite";
1265         android.telephony.satellite.stub.SatelliteDatagram receivedDatagram =
1266                 new android.telephony.satellite.stub.SatelliteDatagram();
1267         receivedDatagram.data = receivedText.getBytes();
1268 
1269         // Verify state transitions: CONNECTED -> TRANSFERRING -> CONNECTED
1270         callback.clearModemStates();
1271         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
1272         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 0);
1273 
1274         assertTrue(satelliteDatagramCallback.waitUntilResult(1));
1275         assertArrayEquals(satelliteDatagramCallback.mDatagram.getSatelliteDatagram(),
1276                 receivedText.getBytes());
1277 
1278         int expectedNumberOfEvents = 2;
1279         assertTrue(callback.waitUntilResult(expectedNumberOfEvents));
1280         assertEquals(expectedNumberOfEvents, callback.getTotalCountOfModemStates());
1281         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DATAGRAM_TRANSFERRING,
1282                 callback.getModemState(0));
1283         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED,
1284                 callback.getModemState(1));
1285 
1286         // Expected datagram transfer state transitions: IDLE -> RECEIVE_SUCCESS -> IDLE
1287         assertTrue(transmissionUpdateCallback
1288                 .waitUntilOnReceiveDatagramStateChanged(2));
1289         assertThat(transmissionUpdateCallback.getNumOfReceiveDatagramStateChanges())
1290                 .isEqualTo(2);
1291         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
1292                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1293                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_SUCCESS,
1294                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1295         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(1)).isEqualTo(
1296                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1297                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
1298                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1299 
1300         sSatelliteManager.unregisterForIncomingDatagram(satelliteDatagramCallback);
1301         stopTransmissionUpdates(transmissionUpdateCallback);
1302     }
1303 
1304     @Test
testSatelliteEnableErrorHandling()1305     public void testSatelliteEnableErrorHandling() {
1306         if (!shouldTestSatelliteWithMockService()) return;
1307         assumeTrue(sTelephonyManager != null);
1308 
1309         grantSatellitePermission();
1310         assertTrue(isSatelliteProvisioned());
1311 
1312         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
1313         boolean originalEnabledState = isSatelliteEnabled();
1314         boolean registerCallback = false;
1315         if (originalEnabledState) {
1316             registerCallback = true;
1317 
1318             long registerResult = sSatelliteManager.registerForModemStateChanged(
1319                     getContext().getMainExecutor(), callback);
1320             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
1321             assertTrue(callback.waitUntilResult(1));
1322 
1323             requestSatelliteEnabled(false);
1324 
1325             assertTrue(callback.waitUntilModemOff());
1326             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
1327             assertFalse(isSatelliteEnabled());
1328             callback.clearModemStates();
1329         }
1330         if (!registerCallback) {
1331             long registerResult = sSatelliteManager
1332                     .registerForModemStateChanged(getContext().getMainExecutor(),
1333                             callback);
1334             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
1335             assertTrue(callback.waitUntilResult(1));
1336             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
1337         }
1338 
1339         callback.clearModemStates();
1340         requestSatelliteEnabled(true, true, SatelliteManager.SATELLITE_RESULT_SUCCESS);
1341         assertTrue(callback.waitUntilResult(2));
1342         assertEquals(2, callback.getTotalCountOfModemStates());
1343         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
1344                 callback.getModemState(0));
1345         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.getModemState(1));
1346         assertTrue(isSatelliteEnabled());
1347 
1348         requestSatelliteEnabled(true, true, SatelliteManager.SATELLITE_RESULT_SUCCESS);
1349         requestSatelliteEnabled(true, false, SatelliteManager.SATELLITE_RESULT_INVALID_ARGUMENTS);
1350 
1351         callback.clearModemStates();
1352         turnRadioOff();
1353         grantSatellitePermission();
1354         assertTrue(callback.waitUntilResult(2));
1355         assertEquals(2, callback.getTotalCountOfModemStates());
1356         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DISABLING_SATELLITE,
1357                 callback.getModemState(0));
1358         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.getModemState(1));
1359         assertFalse(isSatelliteEnabled());
1360 
1361         requestSatelliteEnabled(true, true, SatelliteManager.SATELLITE_RESULT_INVALID_MODEM_STATE);
1362         requestSatelliteEnabled(false);
1363 
1364         turnRadioOn();
1365         grantSatellitePermission();
1366         assertFalse(callback.waitUntilResult(2));
1367         assertEquals(2, callback.getTotalCountOfModemStates());
1368         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DISABLING_SATELLITE,
1369                 callback.getModemState(0));
1370         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.getModemState(1));
1371         assertFalse(isSatelliteEnabled());
1372 
1373         callback.clearModemStates();
1374         requestSatelliteEnabled(true, true, SatelliteManager.SATELLITE_RESULT_SUCCESS);
1375         assertTrue(callback.waitUntilResult(2));
1376         assertEquals(2, callback.getTotalCountOfModemStates());
1377         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
1378                 callback.getModemState(0));
1379         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.getModemState(1));
1380         assertTrue(isSatelliteEnabled());
1381 
1382         callback.clearModemStates();
1383         requestSatelliteEnabled(false);
1384         assertTrue(callback.waitUntilModemOff());
1385         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
1386         assertFalse(isSatelliteEnabled());
1387 
1388         sSatelliteManager.unregisterForModemStateChanged(callback);
1389         revokeSatellitePermission();
1390     }
1391 
1392     @Test
testSatelliteDatagramReceivedAck()1393     public void testSatelliteDatagramReceivedAck() {
1394         if (!shouldTestSatelliteWithMockService()) return;
1395 
1396         grantSatellitePermission();
1397 
1398         assertTrue(isSatelliteProvisioned());
1399 
1400         SatelliteDatagramCallbackTest satelliteDatagramCallback =
1401                 new SatelliteDatagramCallbackTest();
1402         sSatelliteManager.registerForIncomingDatagram(
1403                 getContext().getMainExecutor(), satelliteDatagramCallback);
1404 
1405         String receivedText = "This is a test datagram message from satellite";
1406         android.telephony.satellite.stub.SatelliteDatagram receivedDatagram =
1407                 new android.telephony.satellite.stub.SatelliteDatagram();
1408         receivedDatagram.data = receivedText.getBytes();
1409         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 0);
1410 
1411         assertTrue(satelliteDatagramCallback.waitUntilResult(1));
1412         assertArrayEquals(satelliteDatagramCallback.mDatagram.getSatelliteDatagram(),
1413                 receivedText.getBytes());
1414 
1415         // Compute next received datagramId using current ID and verify it is correct.
1416         long nextDatagramId = ((satelliteDatagramCallback.mDatagramId + 1)
1417                 % DatagramController.MAX_DATAGRAM_ID);
1418         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 0);
1419         assertTrue(satelliteDatagramCallback.waitUntilResult(1));
1420         assertThat(satelliteDatagramCallback.mDatagramId).isEqualTo(nextDatagramId);
1421 
1422         sSatelliteManager.unregisterForIncomingDatagram(satelliteDatagramCallback);
1423         revokeSatellitePermission();
1424     }
1425 
1426     @Test
testRequestSatelliteCapabilities()1427     public void  testRequestSatelliteCapabilities() {
1428         if (!shouldTestSatelliteWithMockService()) return;
1429 
1430         logd("testRequestSatelliteCapabilities");
1431         grantSatellitePermission();
1432 
1433         assertTrue(isSatelliteProvisioned());
1434 
1435         final AtomicReference<SatelliteCapabilities> capabilities = new AtomicReference<>();
1436         final AtomicReference<Integer> errorCode = new AtomicReference<>();
1437         OutcomeReceiver<SatelliteCapabilities, SatelliteManager.SatelliteException> receiver =
1438                 new OutcomeReceiver<>() {
1439                     @Override
1440                     public void onResult(SatelliteCapabilities result) {
1441                         logd("testRequestSatelliteCapabilities: onResult");
1442                         capabilities.set(result);
1443 
1444                         assertNotNull(result);
1445                         assertNotNull(result.getSupportedRadioTechnologies());
1446                         assertThat(SUPPORTED_RADIO_TECHNOLOGIES)
1447                                 .isEqualTo(result.getSupportedRadioTechnologies());
1448                         assertThat(POINTING_TO_SATELLITE_REQUIRED)
1449                                 .isEqualTo(result.isPointingRequired());
1450                         assertThat(MAX_BYTES_PER_DATAGRAM)
1451                                 .isEqualTo(result.getMaxBytesPerOutgoingDatagram());
1452                         assertNotNull(result.getAntennaPositionMap());
1453                         assertThat(ANTENNA_POSITION_MAP).isEqualTo(result.getAntennaPositionMap());
1454                     }
1455 
1456                     @Override
1457                     public void onError(SatelliteManager.SatelliteException exception) {
1458                         logd("testRequestSatelliteCapabilities: onError");
1459                         errorCode.set(exception.getErrorCode());
1460                     }
1461                 };
1462 
1463         sMockSatelliteServiceManager.setSupportedRadioTechnologies(
1464                 new int[]{NTRadioTechnology.PROPRIETARY});
1465         sSatelliteManager.requestCapabilities(getContext().getMainExecutor(), receiver);
1466 
1467         revokeSatellitePermission();
1468     }
1469 
1470     @Test
testSendSatelliteDatagram_success()1471     public void testSendSatelliteDatagram_success() {
1472         if (!shouldTestSatelliteWithMockService()) return;
1473 
1474         logd("testSendSatelliteDatagram_success");
1475         grantSatellitePermission();
1476         assertTrue(isSatelliteProvisioned());
1477 
1478         for (int i = 0; i < 5; i++) {
1479             logd("testSendSatelliteDatagram_success: moveToSendingState");
1480             assertTrue(isSatelliteEnabled());
1481             moveToSendingState();
1482 
1483             logd("testSendSatelliteDatagram_success: Disable satellite");
1484             SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
1485             long registerResult = sSatelliteManager.registerForModemStateChanged(
1486                     getContext().getMainExecutor(), callback);
1487             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
1488             assertTrue(callback.waitUntilResult(1));
1489 
1490             SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
1491                     startTransmissionUpdates();
1492             requestSatelliteEnabled(false);
1493             assertTrue(callback.waitUntilModemOff());
1494             assertFalse(isSatelliteEnabled());
1495             callback.clearModemStates();
1496 
1497             // Datagram transfer state should change from SENDING to FAILED and then IDLE.
1498             assertTrue(transmissionUpdateCallback.waitUntilOnSendDatagramStateChanged(2));
1499             assertThat(transmissionUpdateCallback.getNumOfSendDatagramStateChanges()).isEqualTo(2);
1500             assertThat(transmissionUpdateCallback.getSendDatagramStateChange(0)).isEqualTo(
1501                     new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1502                             SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
1503                             1, SatelliteManager.SATELLITE_RESULT_REQUEST_ABORTED));
1504             assertThat(transmissionUpdateCallback.getSendDatagramStateChange(1)).isEqualTo(
1505                     new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1506                             SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
1507                             0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1508             stopTransmissionUpdates(transmissionUpdateCallback);
1509 
1510             logd("testSendSatelliteDatagram_success: Enable satellite");
1511             requestSatelliteEnabled(true);
1512             assertTrue(callback.waitUntilResult(2));
1513             assertTrue(isSatelliteEnabled());
1514             sSatelliteManager.unregisterForModemStateChanged(callback);
1515 
1516             logd("testSendSatelliteDatagram_success: sendSatelliteDatagramSuccess");
1517             sendSatelliteDatagramSuccess(true, true);
1518         }
1519         revokeSatellitePermission();
1520     }
1521 
1522     @Test
testSendSatelliteDatagram_failure()1523     public void testSendSatelliteDatagram_failure() {
1524         if (!shouldTestSatelliteWithMockService()) return;
1525 
1526         logd("testSendSatelliteDatagram_failure");
1527         grantSatellitePermission();
1528         assertTrue(isSatelliteProvisioned());
1529 
1530         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
1531         SatelliteTransmissionUpdateCallbackTest callback =
1532                 new SatelliteTransmissionUpdateCallbackTest();
1533         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
1534                 resultListener::offer, callback);
1535         Integer errorCode;
1536         try {
1537             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1538         } catch (InterruptedException ex) {
1539             fail("testSendSatelliteDatagram_failure: Got InterruptedException in waiting"
1540                     + " for the startSatelliteTransmissionUpdates result code");
1541             return;
1542         }
1543         assertNotNull(errorCode);
1544         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
1545 
1546         // Send satellite datagram
1547         String mText = "This is a test datagram message from user";
1548         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
1549         callback.clearSendDatagramStateChanges();
1550         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_ERROR);
1551         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
1552                 datagram, true, getContext().getMainExecutor(),
1553                 resultListener::offer);
1554 
1555         try {
1556             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1557         } catch (InterruptedException ex) {
1558             fail("testSendSatelliteDatagram_failure: Got InterruptedException in waiting"
1559                     + " for the sendDatagram result code");
1560             return;
1561         }
1562         assertNotNull(errorCode);
1563         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_ERROR);
1564 
1565         /*
1566          * Send datagram transfer state should have the following transitions:
1567          * 1) SENDING to SENDING_FAILED
1568          * 2) SENDING_FAILED to IDLE
1569          */
1570         int expectedNumOfEvents = 3;
1571         assertTrue(callback.waitUntilOnSendDatagramStateChanged(expectedNumOfEvents));
1572         assertThat(callback.getNumOfSendDatagramStateChanges()).isEqualTo(expectedNumOfEvents);
1573         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
1574                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1575                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
1576                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1577         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
1578                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1579                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
1580                         0, SatelliteManager.SATELLITE_RESULT_ERROR));
1581         assertThat(callback.getSendDatagramStateChange(2)).isEqualTo(
1582                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1583                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
1584                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1585 
1586         callback.clearSendDatagramStateChanges();
1587         sSatelliteManager.stopTransmissionUpdates(callback, getContext().getMainExecutor(),
1588                 resultListener::offer);
1589         revokeSatellitePermission();
1590     }
1591 
1592     @Test
testSendMultipleSatelliteDatagrams_success()1593     public void testSendMultipleSatelliteDatagrams_success() {
1594         if (!shouldTestSatelliteWithMockService()) return;
1595 
1596         logd("testSendMultipleSatelliteDatagrams_success");
1597         grantSatellitePermission();
1598         assertTrue(isSatelliteProvisioned());
1599 
1600         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
1601         SatelliteTransmissionUpdateCallbackTest callback =
1602                 new SatelliteTransmissionUpdateCallbackTest();
1603         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
1604                 resultListener::offer, callback);
1605         Integer errorCode;
1606         try {
1607             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1608         } catch (InterruptedException ex) {
1609             fail("testSendMultipleSatelliteDatagrams_success: Got InterruptedException in waiting"
1610                     + " for the sendDatagram result code");
1611             return;
1612         }
1613         assertNotNull(errorCode);
1614         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
1615 
1616         String mText = "This is a test datagram message from user";
1617         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
1618         callback.clearSendDatagramStateChanges();
1619         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
1620 
1621         // Wait to process datagrams so that datagrams are added to pending list.
1622         sMockSatelliteServiceManager.setWaitToSend(true);
1623 
1624         // Send three datagrams to observe how pendingCount is updated
1625         // after processing one datagram at a time.
1626         LinkedBlockingQueue<Integer> resultListener1 = new LinkedBlockingQueue<>(1);
1627         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
1628                 datagram, true, getContext().getMainExecutor(),
1629                 resultListener1::offer);
1630         assertTrue(callback.waitUntilOnSendDatagramStateChanged(1));
1631         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
1632                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1633                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
1634                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1635 
1636         callback.clearSendDatagramStateChanges();
1637         LinkedBlockingQueue<Integer> resultListener2 = new LinkedBlockingQueue<>(1);
1638         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
1639                 datagram, true, getContext().getMainExecutor(),
1640                 resultListener2::offer);
1641         LinkedBlockingQueue<Integer> resultListener3 = new LinkedBlockingQueue<>(1);
1642         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
1643                 datagram, true, getContext().getMainExecutor(),
1644                 resultListener3::offer);
1645 
1646         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
1647 
1648         // Send first datagram: SENDING to SENDING_SUCCESS
1649         assertTrue(sMockSatelliteServiceManager.sendSavedDatagram());
1650 
1651         try {
1652             errorCode = resultListener1.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1653         } catch (InterruptedException ex) {
1654             fail("testSendMultipleSatelliteDatagrams_success: Got InterruptedException in waiting"
1655                     + " for the sendDatagram result code");
1656             return;
1657         }
1658         assertNotNull(errorCode);
1659         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
1660 
1661         int expectedNumOfEvents = 1;
1662         assertTrue(callback.waitUntilOnSendDatagramStateChanged(expectedNumOfEvents));
1663 
1664         // Pending count is 2 as there are 2 datagrams to be sent.
1665         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
1666                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1667                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
1668                         2, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1669 
1670         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
1671 
1672         // Send second datagram: SENDING to SENDING_SUCCESS
1673         // callback.clearSendDatagramStateChanges();
1674         assertTrue(sMockSatelliteServiceManager.sendSavedDatagram());
1675 
1676         try {
1677             errorCode = resultListener2.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1678         } catch (InterruptedException ex) {
1679             fail("testSendMultipleSatelliteDatagrams_success: Got InterruptedException in waiting"
1680                     + " for the sendDatagram result code");
1681             return;
1682         }
1683         assertNotNull(errorCode);
1684         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
1685 
1686         expectedNumOfEvents = 2;
1687         assertTrue(callback.waitUntilOnSendDatagramStateChanged(expectedNumOfEvents));
1688         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
1689                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1690                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
1691                         2, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1692         assertThat(callback.getSendDatagramStateChange(2)).isEqualTo(
1693                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1694                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
1695                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1696 
1697         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
1698 
1699         // Send third datagram: SENDING - SENDING_SUCCESS - IDLE
1700         assertTrue(sMockSatelliteServiceManager.sendSavedDatagram());
1701 
1702         try {
1703             errorCode = resultListener3.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1704         } catch (InterruptedException ex) {
1705             fail("testSendMultipleSatelliteDatagrams_success: Got InterruptedException in waiting"
1706                     + " for the sendDatagram result code");
1707             return;
1708         }
1709         assertNotNull(errorCode);
1710         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
1711 
1712         expectedNumOfEvents = 3;
1713         assertTrue(callback.waitUntilOnSendDatagramStateChanged(expectedNumOfEvents));
1714         assertThat(callback.getSendDatagramStateChange(3)).isEqualTo(
1715                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1716                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
1717                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1718         assertThat(callback.getSendDatagramStateChange(4)).isEqualTo(
1719                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1720                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
1721                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1722         assertThat(callback.getSendDatagramStateChange(5)).isEqualTo(
1723                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1724                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
1725                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1726 
1727         callback.clearSendDatagramStateChanges();
1728         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
1729         sMockSatelliteServiceManager.setWaitToSend(false);
1730         sSatelliteManager.stopTransmissionUpdates(callback, getContext().getMainExecutor(),
1731                 resultListener::offer);
1732         revokeSatellitePermission();
1733     }
1734 
1735     @Test
testSendMultipleSatelliteDatagrams_failure()1736     public void testSendMultipleSatelliteDatagrams_failure() {
1737         if (!shouldTestSatelliteWithMockService()) return;
1738 
1739         logd("testSendMultipleSatelliteDatagrams_failure");
1740         grantSatellitePermission();
1741         assertTrue(isSatelliteProvisioned());
1742 
1743         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
1744         SatelliteTransmissionUpdateCallbackTest callback =
1745                 new SatelliteTransmissionUpdateCallbackTest();
1746         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
1747                 resultListener::offer, callback);
1748         Integer errorCode;
1749         try {
1750             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1751         } catch (InterruptedException ex) {
1752             fail("testSendMultipleSatelliteDatagrams_failure: Got InterruptedException in waiting"
1753                     + " for the sendDatagram result code");
1754             return;
1755         }
1756         assertNotNull(errorCode);
1757         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
1758 
1759         String mText = "This is a test datagram message from user";
1760         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
1761         callback.clearSendDatagramStateChanges();
1762         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
1763 
1764         // Wait to process datagrams so that datagrams are added to pending list.
1765         sMockSatelliteServiceManager.setWaitToSend(true);
1766 
1767         // Send three datagrams to observe how pendingCount is updated
1768         // after processing one datagram at a time.
1769         LinkedBlockingQueue<Integer> resultListener1 = new LinkedBlockingQueue<>(1);
1770         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
1771                 datagram, true, getContext().getMainExecutor(),
1772                 resultListener1::offer);
1773         assertTrue(callback.waitUntilOnSendDatagramStateChanged(1));
1774         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
1775                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1776                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
1777                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1778 
1779         callback.clearSendDatagramStateChanges();
1780         LinkedBlockingQueue<Integer> resultListener2 = new LinkedBlockingQueue<>(1);
1781         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
1782                 datagram, true, getContext().getMainExecutor(),
1783                 resultListener2::offer);
1784         LinkedBlockingQueue<Integer> resultListener3 = new LinkedBlockingQueue<>(1);
1785         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
1786                 datagram, true, getContext().getMainExecutor(),
1787                 resultListener3::offer);
1788 
1789         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
1790 
1791         // Set error and send first datagram: SENDING to SENDING_FAILED
1792         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_ERROR);
1793         assertTrue(sMockSatelliteServiceManager.sendSavedDatagram());
1794 
1795         try {
1796             errorCode = resultListener1.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1797         } catch (InterruptedException ex) {
1798             fail("testSendMultipleSatelliteDatagrams_success: Got InterruptedException in waiting"
1799                     + " for the sendDatagram result code");
1800             return;
1801         }
1802         assertNotNull(errorCode);
1803         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_ERROR);
1804 
1805         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
1806 
1807         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_SUCCESS);
1808         assertTrue(sMockSatelliteServiceManager.sendSavedDatagram());
1809         try {
1810             errorCode = resultListener2.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1811         } catch (InterruptedException ex) {
1812             fail("testSendMultipleSatelliteDatagrams_success: Got InterruptedException in waiting"
1813                     + " for the sendDatagram result code");
1814             return;
1815         }
1816         assertNotNull(errorCode);
1817         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
1818 
1819 
1820         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
1821         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_SUCCESS);
1822         assertTrue(sMockSatelliteServiceManager.sendSavedDatagram());
1823         try {
1824             errorCode = resultListener3.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1825         } catch (InterruptedException ex) {
1826             fail("testSendMultipleSatelliteDatagrams_success: Got InterruptedException in waiting"
1827                     + " for the sendDatagram result code");
1828             return;
1829         }
1830         assertNotNull(errorCode);
1831         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
1832 
1833         assertTrue(callback.waitUntilOnSendDatagramStateChanged(4));
1834         // Pending count is 2 as there are 2 datagrams to be sent.
1835         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
1836                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1837                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
1838                         2, SatelliteManager.SATELLITE_RESULT_ERROR));
1839         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
1840                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1841                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
1842                         2, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1843         assertThat(callback.getSendDatagramStateChange(2)).isEqualTo(
1844                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1845                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
1846                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1847         assertThat(callback.getSendDatagramStateChange(4)).isEqualTo(
1848                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1849                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
1850                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1851 
1852         callback.clearSendDatagramStateChanges();
1853         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
1854         sMockSatelliteServiceManager.setWaitToSend(false);
1855         sSatelliteManager.stopTransmissionUpdates(callback, getContext().getMainExecutor(),
1856                 resultListener::offer);
1857         revokeSatellitePermission();
1858     }
1859 
1860 
1861     @Test
testReceiveSatelliteDatagram()1862     public void testReceiveSatelliteDatagram() {
1863         if (!shouldTestSatelliteWithMockService()) return;
1864 
1865         logd("testReceiveSatelliteDatagram");
1866         grantSatellitePermission();
1867         assertTrue(isSatelliteProvisioned());
1868 
1869         for (int i = 0; i < 5; i++) {
1870             logd("testReceiveSatelliteDatagram: moveToReceivingState");
1871             assertTrue(isSatelliteEnabled());
1872             moveToReceivingState();
1873 
1874             logd("testReceiveSatelliteDatagram: Disable satellite");
1875             SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
1876             long registerResult = sSatelliteManager.registerForModemStateChanged(
1877                     getContext().getMainExecutor(), callback);
1878             assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
1879             assertTrue(callback.waitUntilResult(1));
1880 
1881             SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
1882                     startTransmissionUpdates();
1883             requestSatelliteEnabled(false);
1884             assertTrue(callback.waitUntilModemOff());
1885             assertFalse(isSatelliteEnabled());
1886             callback.clearModemStates();
1887 
1888             // Datagram transfer state should change from RECEIVING to IDLE.
1889             assertTrue(transmissionUpdateCallback
1890                     .waitUntilOnReceiveDatagramStateChanged(2));
1891             assertThat(transmissionUpdateCallback.getNumOfReceiveDatagramStateChanges())
1892                     .isEqualTo(2);
1893             assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
1894                     new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1895                             SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_FAILED,
1896                             0, SatelliteManager.SATELLITE_RESULT_REQUEST_ABORTED));
1897             assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(1)).isEqualTo(
1898                     new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1899                             SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
1900                             0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1901             stopTransmissionUpdates(transmissionUpdateCallback);
1902 
1903             logd("testReceiveSatelliteDatagram: Enable satellite");
1904             requestSatelliteEnabled(true);
1905             assertTrue(callback.waitUntilResult(1));
1906             assertTrue(isSatelliteEnabled());
1907             sSatelliteManager.unregisterForModemStateChanged(callback);
1908 
1909             logd("testReceiveSatelliteDatagram: receiveSatelliteDatagramSuccess");
1910             receiveSatelliteDatagramSuccess();
1911         }
1912         revokeSatellitePermission();
1913     }
1914 
1915     @Test
testReceiveMultipleSatelliteDatagrams()1916     public void testReceiveMultipleSatelliteDatagrams() {
1917         if (!shouldTestSatelliteWithMockService()) return;
1918 
1919         logd("testReceiveMultipleSatelliteDatagrams");
1920         grantSatellitePermission();
1921         assertTrue(isSatelliteProvisioned());
1922 
1923         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
1924         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
1925                 new SatelliteTransmissionUpdateCallbackTest();
1926         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
1927                 resultListener::offer, transmissionUpdateCallback);
1928         Integer errorCode;
1929         try {
1930             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
1931         } catch (InterruptedException ex) {
1932             fail("testReceiveMultipleSatelliteDatagrams: Got InterruptedException in waiting"
1933                     + " for the startSatelliteTransmissionUpdates result code");
1934             return;
1935         }
1936         assertNotNull(errorCode);
1937         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
1938 
1939         SatelliteDatagramCallbackTest satelliteDatagramCallback =
1940                 new SatelliteDatagramCallbackTest();
1941         sSatelliteManager.registerForIncomingDatagram(
1942                 getContext().getMainExecutor(), satelliteDatagramCallback);
1943 
1944         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
1945         sMockSatelliteServiceManager.sendOnPendingDatagrams();
1946         assertTrue(sMockSatelliteServiceManager.waitForEventOnPollPendingSatelliteDatagrams(1));
1947 
1948         // Receive first datagram: Datagram state changes from RECEIVING to RECEIVE_SUCCESS
1949         String receivedText = "This is a test datagram message from satellite";
1950         android.telephony.satellite.stub.SatelliteDatagram receivedDatagram =
1951                 new android.telephony.satellite.stub.SatelliteDatagram();
1952         receivedDatagram.data = receivedText.getBytes();
1953         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 2);
1954         assertTrue(satelliteDatagramCallback.waitUntilResult(1));
1955         assertArrayEquals(satelliteDatagramCallback.mDatagram.getSatelliteDatagram(),
1956                 receivedText.getBytes());
1957         int expectedNumOfEvents = 2;
1958         assertTrue(transmissionUpdateCallback
1959                 .waitUntilOnReceiveDatagramStateChanged(expectedNumOfEvents));
1960         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
1961                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1962                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVING,
1963                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1964         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(1)).isEqualTo(
1965                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1966                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_SUCCESS,
1967                         2, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1968 
1969 
1970         // Receive second datagram: Datagram state changes from RECEIVING to RECEIVE_SUCCESS
1971         assertTrue(sMockSatelliteServiceManager.waitForEventOnPollPendingSatelliteDatagrams(1));
1972         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 1);
1973         assertTrue(satelliteDatagramCallback.waitUntilResult(1));
1974         assertArrayEquals(satelliteDatagramCallback.mDatagram.getSatelliteDatagram(),
1975                 receivedText.getBytes());
1976         expectedNumOfEvents = 2;
1977         assertTrue(transmissionUpdateCallback
1978                 .waitUntilOnReceiveDatagramStateChanged(2));
1979         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(2)).isEqualTo(
1980                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1981                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVING,
1982                         2, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1983         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(3)).isEqualTo(
1984                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1985                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_SUCCESS,
1986                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
1987 
1988         // Receive third datagram: Datagram state changes from RECEIVING - RECEIVE_SUCCESS - IDLE
1989         assertTrue(sMockSatelliteServiceManager.waitForEventOnPollPendingSatelliteDatagrams(1));
1990         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 0);
1991         assertTrue(satelliteDatagramCallback.waitUntilResult(1));
1992         assertArrayEquals(satelliteDatagramCallback.mDatagram.getSatelliteDatagram(),
1993                 receivedText.getBytes());
1994         expectedNumOfEvents = 3;
1995         assertTrue(transmissionUpdateCallback
1996                 .waitUntilOnReceiveDatagramStateChanged(3));
1997         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(4)).isEqualTo(
1998                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
1999                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVING,
2000                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2001         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(5)).isEqualTo(
2002                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2003                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_SUCCESS,
2004                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2005         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(6)).isEqualTo(
2006                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2007                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
2008                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2009 
2010         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
2011         sSatelliteManager.stopTransmissionUpdates(transmissionUpdateCallback,
2012                 getContext().getMainExecutor(), resultListener::offer);
2013         sSatelliteManager.unregisterForIncomingDatagram(satelliteDatagramCallback);
2014         revokeSatellitePermission();
2015     }
2016 
2017     @Test
testReceiveSatellitePositionUpdate()2018     public void testReceiveSatellitePositionUpdate() {
2019         if (!shouldTestSatelliteWithMockService()) return;
2020 
2021         logd("testReceiveSatellitePositionUpdate");
2022         grantSatellitePermission();
2023         assertTrue(isSatelliteProvisioned());
2024 
2025         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
2026         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
2027                 new SatelliteTransmissionUpdateCallbackTest();
2028         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
2029                 resultListener::offer, transmissionUpdateCallback);
2030         Integer errorCode;
2031         try {
2032             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2033         } catch (InterruptedException ex) {
2034             fail("testReceiveSatellitePositionUpdate: Got InterruptedException in waiting"
2035                     + " for the startSatelliteTransmissionUpdates result code");
2036             return;
2037         }
2038         assertNotNull(errorCode);
2039         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
2040 
2041         transmissionUpdateCallback.clearPointingInfo();
2042         android.telephony.satellite.stub.PointingInfo pointingInfo =
2043                 new android.telephony.satellite.stub.PointingInfo();
2044         pointingInfo.satelliteAzimuth = 10.5f;
2045         pointingInfo.satelliteElevation = 30.23f;
2046         PointingInfo expectedPointingInfo = new PointingInfo(10.5f, 30.23f);
2047         sMockSatelliteServiceManager.sendOnSatellitePositionChanged(pointingInfo);
2048         assertTrue(transmissionUpdateCallback.waitUntilOnSatellitePositionChanged(1));
2049         assertThat(transmissionUpdateCallback.mPointingInfo.getSatelliteAzimuthDegrees())
2050                 .isEqualTo(expectedPointingInfo.getSatelliteAzimuthDegrees());
2051         assertThat(transmissionUpdateCallback.mPointingInfo.getSatelliteElevationDegrees())
2052                 .isEqualTo(expectedPointingInfo.getSatelliteElevationDegrees());
2053 
2054         transmissionUpdateCallback.clearPointingInfo();
2055         sSatelliteManager.stopTransmissionUpdates(transmissionUpdateCallback,
2056                 getContext().getMainExecutor(), resultListener::offer);
2057         revokeSatellitePermission();
2058     }
2059 
2060     @Test
testReceiveMultipleSatellitePositionUpdates()2061     public void testReceiveMultipleSatellitePositionUpdates() {
2062         if (!shouldTestSatelliteWithMockService()) return;
2063 
2064         logd("testReceiveMultipleSatellitePositionUpdates");
2065         grantSatellitePermission();
2066         assertTrue(isSatelliteProvisioned());
2067 
2068         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
2069         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
2070                 new SatelliteTransmissionUpdateCallbackTest();
2071         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
2072                 resultListener::offer, transmissionUpdateCallback);
2073         Integer errorCode;
2074         try {
2075             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2076         } catch (InterruptedException ex) {
2077             fail("testReceiveMultipleSatellitePositionUpdates: Got InterruptedException in waiting"
2078                     + " for the startSatelliteTransmissionUpdates result code");
2079             return;
2080         }
2081         assertNotNull(errorCode);
2082         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
2083 
2084         // Receive first position update
2085         transmissionUpdateCallback.clearPointingInfo();
2086         android.telephony.satellite.stub.PointingInfo pointingInfo =
2087                 new android.telephony.satellite.stub.PointingInfo();
2088         pointingInfo.satelliteAzimuth = 10.5f;
2089         pointingInfo.satelliteElevation = 30.23f;
2090         PointingInfo expectedPointingInfo = new PointingInfo(10.5f, 30.23f);
2091         sMockSatelliteServiceManager.sendOnSatellitePositionChanged(pointingInfo);
2092         assertTrue(transmissionUpdateCallback.waitUntilOnSatellitePositionChanged(1));
2093         assertThat(transmissionUpdateCallback.mPointingInfo.getSatelliteAzimuthDegrees())
2094                 .isEqualTo(expectedPointingInfo.getSatelliteAzimuthDegrees());
2095         assertThat(transmissionUpdateCallback.mPointingInfo.getSatelliteElevationDegrees())
2096                 .isEqualTo(expectedPointingInfo.getSatelliteElevationDegrees());
2097 
2098         // Receive second position update
2099         transmissionUpdateCallback.clearPointingInfo();
2100         pointingInfo.satelliteAzimuth = 100;
2101         pointingInfo.satelliteElevation = 120;
2102         expectedPointingInfo = new PointingInfo(100, 120);
2103         sMockSatelliteServiceManager.sendOnSatellitePositionChanged(pointingInfo);
2104         assertTrue(transmissionUpdateCallback.waitUntilOnSatellitePositionChanged(1));
2105         assertThat(transmissionUpdateCallback.mPointingInfo.getSatelliteAzimuthDegrees())
2106                 .isEqualTo(expectedPointingInfo.getSatelliteAzimuthDegrees());
2107         assertThat(transmissionUpdateCallback.mPointingInfo.getSatelliteElevationDegrees())
2108                 .isEqualTo(expectedPointingInfo.getSatelliteElevationDegrees());
2109 
2110         transmissionUpdateCallback.clearPointingInfo();
2111         sSatelliteManager.stopTransmissionUpdates(transmissionUpdateCallback,
2112                 getContext().getMainExecutor(), resultListener::offer);
2113         revokeSatellitePermission();
2114     }
2115 
2116     @Test
testSendAndReceiveSatelliteDatagram_DemoMode_success()2117     public void testSendAndReceiveSatelliteDatagram_DemoMode_success() {
2118         if (!shouldTestSatelliteWithMockService()) return;
2119 
2120         logd("testSendSatelliteDatagram_DemoMode_success");
2121         grantSatellitePermission();
2122         assertTrue(isSatelliteProvisioned());
2123         assertTrue(sMockSatelliteServiceManager.overrideSatellitePointingUiClassName());
2124 
2125         String mText = "This is a test datagram message from user";
2126         for (int i = 0; i < 5; i++) {
2127             logd("testSendSatelliteDatagram_DemoMode_success: moveToSendingState");
2128             assertTrue(isSatelliteEnabled());
2129             moveToSendingState();
2130 
2131             logd("testSendSatelliteDatagram_DemoMode_success: Disable satellite");
2132             SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
2133             sSatelliteManager.registerForModemStateChanged(
2134                     getContext().getMainExecutor(), stateCallback);
2135             assertTrue(stateCallback.waitUntilResult(1));
2136 
2137             SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
2138                     startTransmissionUpdates();
2139             requestSatelliteEnabled(false);
2140             assertTrue(stateCallback.waitUntilModemOff());
2141             assertFalse(isSatelliteEnabled());
2142             stateCallback.clearModemStates();
2143 
2144             // Datagram transfer state should change from SENDING to FAILED and then IDLE.
2145             assertTrue(transmissionUpdateCallback.waitUntilOnSendDatagramStateChanged(2));
2146             assertThat(transmissionUpdateCallback.getNumOfSendDatagramStateChanges()).isEqualTo(2);
2147             assertThat(transmissionUpdateCallback.getSendDatagramStateChange(0)).isEqualTo(
2148                     new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2149                             SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
2150                             1, SatelliteManager.SATELLITE_RESULT_REQUEST_ABORTED));
2151             assertThat(transmissionUpdateCallback.getSendDatagramStateChange(1)).isEqualTo(
2152                     new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2153                             SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
2154                             0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2155             stopTransmissionUpdates(transmissionUpdateCallback);
2156 
2157             logd("testSendSatelliteDatagram_DemoMode_success: Enable satellite");
2158             stateCallback.clearModemStates();
2159             requestSatelliteEnabledForDemoMode(true);
2160             assertTrue(stateCallback.waitUntilResult(2));
2161             assertTrue(isSatelliteEnabled());
2162             assertTrue(getIsEmergency());
2163             sSatelliteManager.unregisterForModemStateChanged(stateCallback);
2164 
2165             logd("testSendSatelliteDatagram_DemoMode_success: sendSatelliteDatagramSuccess");
2166             assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(false,
2167                     DatagramController.TIMEOUT_TYPE_DATAGRAM_DELAY_IN_DEMO_MODE,
2168                     TEST_DATAGRAM_DELAY_IN_DEMO_MODE_TIMEOUT_LONG_MILLIS));
2169             sendSatelliteDatagramDemoModeSuccess(mText);
2170 
2171             // Automatically triggering pollPendingSatelliteDatagrams after successfully sending
2172             // a callback back to sendSatelliteDatagram for demo mode
2173             sSatelliteManager.setDeviceAlignedWithSatellite(true);
2174             transmissionUpdateCallback = startTransmissionUpdates();
2175             SatelliteDatagramCallbackTest datagramCallback = new SatelliteDatagramCallbackTest();
2176             assertTrue(SatelliteManager.SATELLITE_RESULT_SUCCESS
2177                     == sSatelliteManager.registerForIncomingDatagram(getContext().getMainExecutor(),
2178                     datagramCallback));
2179 
2180             // Because pending count is 0, datagram transfer state changes from
2181             // IDLE -> RECEIVING -> RECEIVE_SUCCESS -> IDLE.
2182             int expectedNumOfEvents = 3;
2183             assertTrue(transmissionUpdateCallback
2184                     .waitUntilOnReceiveDatagramStateChanged(expectedNumOfEvents));
2185             assertThat(transmissionUpdateCallback.getNumOfReceiveDatagramStateChanges())
2186                     .isEqualTo(expectedNumOfEvents);
2187             assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
2188                     new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2189                             SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVING,
2190                             0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2191             assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(1)).isEqualTo(
2192                     new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2193                             SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_SUCCESS,
2194                             0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2195             assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(2)).isEqualTo(
2196                     new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2197                             SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
2198                             0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2199 
2200             datagramCallback.waitUntilResult(1);
2201             // Because demo mode is on, the received datagram should be the same as the
2202             // last sent datagram
2203             datagramCallback.waitUntilResult(1);
2204             assertTrue(Arrays.equals(
2205                     datagramCallback.mDatagram.getSatelliteDatagram(), mText.getBytes()));
2206             sSatelliteManager.unregisterForIncomingDatagram(datagramCallback);
2207             transmissionUpdateCallback.clearReceiveDatagramStateChanges();
2208             stopTransmissionUpdates(transmissionUpdateCallback);
2209         }
2210 
2211         sSatelliteManager.setDeviceAlignedWithSatellite(false);
2212         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(true,
2213                 DatagramController.TIMEOUT_TYPE_DATAGRAM_DELAY_IN_DEMO_MODE, 0));
2214         assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
2215         revokeSatellitePermission();
2216     }
2217 
2218     @Test
testSendAndReceiveMultipleSatelliteDatagrams_DemoMode_success()2219     public void testSendAndReceiveMultipleSatelliteDatagrams_DemoMode_success() {
2220         if (!shouldTestSatelliteWithMockService()) return;
2221 
2222         logd("testSendAndReceiveMultipleSatelliteDatagrams_DemoMode_success");
2223         grantSatellitePermission();
2224         assertTrue(isSatelliteProvisioned());
2225         assertTrue(sMockSatelliteServiceManager.overrideSatellitePointingUiClassName());
2226         assertTrue(sMockSatelliteServiceManager.setShouldSendDatagramToModemInDemoMode(false));
2227 
2228         // Enable demo mode
2229         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
2230         sSatelliteManager.registerForModemStateChanged(
2231                 getContext().getMainExecutor(), stateCallback);
2232         assertTrue(stateCallback.waitUntilResult(1));
2233         requestSatelliteEnabled(false);
2234         assertTrue(stateCallback.waitUntilModemOff());
2235         assertFalse(isSatelliteEnabled());
2236         stateCallback.clearModemStates();
2237         requestSatelliteEnabledForDemoMode(true);
2238         assertTrue(stateCallback.waitUntilResult(2));
2239         assertTrue(isSatelliteEnabled());
2240         sSatelliteManager.setDeviceAlignedWithSatellite(true);
2241 
2242         SatelliteDatagramCallbackTest datagramCallback = new SatelliteDatagramCallbackTest();
2243         assertTrue(SatelliteManager.SATELLITE_RESULT_SUCCESS
2244                 == sSatelliteManager.registerForIncomingDatagram(getContext().getMainExecutor(),
2245                 datagramCallback));
2246 
2247         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(false,
2248                 DatagramController.TIMEOUT_TYPE_DATAGRAM_DELAY_IN_DEMO_MODE,
2249                 TEST_DATAGRAM_DELAY_IN_DEMO_MODE_TIMEOUT_LONG_MILLIS));
2250 
2251         String []datagramContentArr = new String[5];
2252         LinkedBlockingQueue<Integer> []resultListenerArr = new LinkedBlockingQueue[5];
2253         for (int i = 0; i < 5; i++) {
2254             datagramContentArr[i] = "This is a test message " + i;
2255             resultListenerArr[i] = new LinkedBlockingQueue<>(1);
2256         }
2257 
2258         // Send satellite datagrams
2259         for (int i = 0; i < 5; i++) {
2260             SatelliteDatagram datagram = new SatelliteDatagram(datagramContentArr[i].getBytes());
2261             sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
2262                     datagram, true, getContext().getMainExecutor(),
2263                     resultListenerArr[i]::offer);
2264         }
2265 
2266         // Wait for the results of the send requests
2267         for (int i = 0; i < 5; i++) {
2268             Integer errorCode;
2269             try {
2270                 errorCode = resultListenerArr[i].poll(TIMEOUT, TimeUnit.MILLISECONDS);
2271             } catch (InterruptedException ex) {
2272                 fail("testSendAndReceiveMultipleSatelliteDatagrams_DemoMode_success: Got "
2273                         + "InterruptedException in waiting for the result of datagram " + i);
2274                 return;
2275             }
2276             assertNotNull(errorCode);
2277             assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
2278         }
2279 
2280         // Wait for the loop-back datagrams
2281         assertTrue(datagramCallback.waitUntilResult(5));
2282         assertEquals(5, datagramCallback.mDatagramList.size());
2283 
2284         // Verify the content of the loop-back datagrams
2285         for (int i = 0; i < 5; i++) {
2286             assertTrue(Arrays.equals(datagramContentArr[i].getBytes(),
2287                     datagramCallback.mDatagramList.get(i).getSatelliteDatagram()));
2288         }
2289 
2290         sSatelliteManager.unregisterForIncomingDatagram(datagramCallback);
2291         sSatelliteManager.setDeviceAlignedWithSatellite(false);
2292         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(true,
2293                 DatagramController.TIMEOUT_TYPE_DATAGRAM_DELAY_IN_DEMO_MODE, 0));
2294         assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
2295         requestSatelliteEnabled(false);
2296         assertTrue(stateCallback.waitUntilModemOff());
2297         revokeSatellitePermission();
2298     }
2299 
2300     @Test
testSendSatelliteDatagram_DemoMode_failure()2301     public void testSendSatelliteDatagram_DemoMode_failure() {
2302         if (!shouldTestSatelliteWithMockService()) return;
2303 
2304         logd("testSendSatelliteDatagram_DemoMode_failure");
2305         grantSatellitePermission();
2306         assertTrue(isSatelliteProvisioned());
2307 
2308         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
2309         sSatelliteManager.registerForModemStateChanged(
2310                 getContext().getMainExecutor(), stateCallback);
2311         assertTrue(stateCallback.waitUntilResult(1));
2312 
2313         // Enable satellite with demo mode on
2314         if (isSatelliteEnabled()) {
2315             requestSatelliteEnabled(false);
2316             assertTrue(stateCallback.waitUntilModemOff());
2317             stateCallback.clearModemStates();
2318         }
2319         requestSatelliteEnabledForDemoMode(true);
2320         assertTrue(stateCallback.waitUntilResult(2));
2321         assertTrue(isSatelliteEnabled());
2322         assertTrue(getIsEmergency());
2323         assertTrue(sMockSatelliteServiceManager.setShouldSendDatagramToModemInDemoMode(true));
2324 
2325         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
2326         SatelliteTransmissionUpdateCallbackTest callback =
2327                 new SatelliteTransmissionUpdateCallbackTest();
2328         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
2329                 resultListener::offer, callback);
2330         Integer errorCode;
2331         try {
2332             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2333         } catch (InterruptedException ex) {
2334             fail("testSendSatelliteDatagram_DemoMode_failure: Got InterruptedException in waiting"
2335                     + " for the startSatelliteTransmissionUpdates result code");
2336             return;
2337         }
2338         assertNotNull(errorCode);
2339         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
2340 
2341         // Send satellite datagram
2342         String mText = "This is a test datagram message from user";
2343         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
2344         callback.clearSendDatagramStateChanges();
2345         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_ERROR);
2346         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
2347                 datagram, true, getContext().getMainExecutor(),
2348                 resultListener::offer);
2349 
2350         try {
2351             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2352         } catch (InterruptedException ex) {
2353             fail("testSendSatelliteDatagram_DemoMode_failure: Got InterruptedException in waiting"
2354                     + " for the sendDatagram result code");
2355             return;
2356         }
2357         assertNotNull(errorCode);
2358         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_ERROR);
2359 
2360         /*
2361          * Send datagram transfer state should have the following transitions:
2362          * 1) IDLE to SENDING
2363          * 2) SENDING to SENDING_FAILED
2364          * 3) SENDING_FAILED to IDLE
2365          */
2366         int expectedNumOfEvents = 3;
2367         assertTrue(callback.waitUntilOnSendDatagramStateChanged(expectedNumOfEvents));
2368         assertThat(callback.getNumOfSendDatagramStateChanges()).isEqualTo(expectedNumOfEvents);
2369         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
2370                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2371                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
2372                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2373         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
2374                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2375                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
2376                         0, SatelliteManager.SATELLITE_RESULT_ERROR));
2377         assertThat(callback.getSendDatagramStateChange(2)).isEqualTo(
2378                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2379                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
2380                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2381 
2382         callback.clearSendDatagramStateChanges();
2383         sSatelliteManager.stopTransmissionUpdates(callback, getContext().getMainExecutor(),
2384                 resultListener::offer);
2385         sSatelliteManager.unregisterForModemStateChanged(stateCallback);
2386         revokeSatellitePermission();
2387     }
2388 
2389     @Test
testSatelliteModeRadios()2390     public void testSatelliteModeRadios() {
2391         if (!shouldTestSatelliteWithMockService()) return;
2392 
2393         logd("testSatelliteModeRadios: start");
2394         InstrumentationRegistry.getInstrumentation().getUiAutomation()
2395                 .adoptShellPermissionIdentity(Manifest.permission.SATELLITE_COMMUNICATION,
2396                         Manifest.permission.WRITE_SECURE_SETTINGS,
2397                         Manifest.permission.UWB_PRIVILEGED);
2398         assertTrue(isSatelliteProvisioned());
2399 
2400         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
2401         sSatelliteManager.registerForModemStateChanged(
2402                 getContext().getMainExecutor(), stateCallback);
2403         assertTrue(stateCallback.waitUntilResult(1));
2404 
2405         boolean originalEnabledState = isSatelliteEnabled();
2406         if (originalEnabledState) {
2407             requestSatelliteEnabled(false);
2408             assertTrue(stateCallback.waitUntilModemOff());
2409             assertSatelliteEnabledInSettings(false);
2410             stateCallback.clearModemStates();
2411         }
2412 
2413         // Get satellite mode radios
2414         String originalSatelliteModeRadios =  Settings.Global.getString(
2415                 getContext().getContentResolver(), Settings.Global.SATELLITE_MODE_RADIOS);
2416         logd("originalSatelliteModeRadios: " + originalSatelliteModeRadios);
2417         SatelliteModeRadiosUpdater satelliteRadiosModeUpdater =
2418                 new SatelliteModeRadiosUpdater(getContext());
2419 
2420         try {
2421             identifyRadiosSensitiveToSatelliteMode();
2422             mTestSatelliteModeRadios = "";
2423             logd("test satelliteModeRadios: " + mTestSatelliteModeRadios);
2424             assertTrue(satelliteRadiosModeUpdater.setSatelliteModeRadios(mTestSatelliteModeRadios));
2425 
2426             // Enable Satellite and check whether all radios are disabled
2427             requestSatelliteEnabled(true, EXTERNAL_DEPENDENT_TIMEOUT);
2428             assertTrue(stateCallback.waitUntilResult(1));
2429             assertSatelliteEnabledInSettings(true);
2430             assertTrue(areAllRadiosDisabled());
2431 
2432             // Disable satellite and check whether all radios are set to their initial state
2433             setRadioExpectedState();
2434             requestSatelliteEnabled(false);
2435             assertTrue(stateCallback.waitUntilResult(1));
2436             assertSatelliteEnabledInSettings(false);
2437             assertTrue(areAllRadiosResetToInitialState());
2438         } finally {
2439             // Restore original satellite mode radios
2440             logd("restore original satellite mode radios");
2441             assertTrue(satelliteRadiosModeUpdater.setSatelliteModeRadios(
2442                     originalSatelliteModeRadios));
2443             sSatelliteManager.unregisterForModemStateChanged(stateCallback);
2444             unregisterSatelliteModeRadios();
2445             InstrumentationRegistry.getInstrumentation().getUiAutomation()
2446                     .dropShellPermissionIdentity();
2447         }
2448     }
2449 
2450     @Test
testSatelliteModeRadios_noRadiosSensitiveToSatelliteMode()2451     public void testSatelliteModeRadios_noRadiosSensitiveToSatelliteMode() {
2452         if (!shouldTestSatelliteWithMockService()) return;
2453 
2454         logd("testSatelliteModeRadios_noRadiosSensitiveToSatelliteMode: start");
2455         InstrumentationRegistry.getInstrumentation().getUiAutomation()
2456                 .adoptShellPermissionIdentity(Manifest.permission.SATELLITE_COMMUNICATION,
2457                         Manifest.permission.WRITE_SECURE_SETTINGS,
2458                         Manifest.permission.UWB_PRIVILEGED);
2459         assertTrue(isSatelliteProvisioned());
2460 
2461         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
2462         sSatelliteManager.registerForModemStateChanged(
2463                 getContext().getMainExecutor(), stateCallback);
2464         assertTrue(stateCallback.waitUntilResult(1));
2465 
2466         boolean originalEnabledState = isSatelliteEnabled();
2467         if (originalEnabledState) {
2468             requestSatelliteEnabled(false);
2469             assertTrue(stateCallback.waitUntilModemOff());
2470             assertSatelliteEnabledInSettings(false);
2471             stateCallback.clearModemStates();
2472         }
2473 
2474         // Get satellite mode radios
2475         String originalSatelliteModeRadios =  Settings.Global.getString(
2476                 getContext().getContentResolver(), Settings.Global.SATELLITE_MODE_RADIOS);
2477         logd("originalSatelliteModeRadios: " + originalSatelliteModeRadios);
2478         SatelliteModeRadiosUpdater satelliteRadiosModeUpdater =
2479                 new SatelliteModeRadiosUpdater(getContext());
2480 
2481         try {
2482             mTestSatelliteModeRadios = "";
2483             logd("test satelliteModeRadios: " + mTestSatelliteModeRadios);
2484             assertTrue(satelliteRadiosModeUpdater.setSatelliteModeRadios(mTestSatelliteModeRadios));
2485 
2486             // Enable Satellite and check whether all radios are disabled
2487             setRadioExpectedState();
2488             requestSatelliteEnabled(true, EXTERNAL_DEPENDENT_TIMEOUT);
2489             assertTrue(stateCallback.waitUntilResult(1));
2490             assertSatelliteEnabledInSettings(true);
2491             assertTrue(areAllRadiosDisabled());
2492             assertTrue(areAllRadiosResetToInitialState());
2493 
2494             // Disable satellite and check whether all radios are set to their initial state
2495             setRadioExpectedState();
2496             stateCallback.clearModemStates();
2497             requestSatelliteEnabled(false);
2498             assertTrue(stateCallback.waitUntilModemOff());
2499             assertSatelliteEnabledInSettings(false);
2500             assertTrue(areAllRadiosResetToInitialState());
2501             stateCallback.clearModemStates();
2502         } finally {
2503             // Restore original satellite mode radios
2504             logd("restore original satellite mode radios");
2505             assertTrue(satelliteRadiosModeUpdater.setSatelliteModeRadios(
2506                     originalSatelliteModeRadios));
2507             sSatelliteManager.unregisterForModemStateChanged(stateCallback);
2508             InstrumentationRegistry.getInstrumentation().getUiAutomation()
2509                     .dropShellPermissionIdentity();
2510         }
2511     }
2512 
2513     @Test
testSatelliteModeRadiosWithAirplaneMode()2514     public void testSatelliteModeRadiosWithAirplaneMode() throws Exception {
2515         if (!shouldTestSatelliteWithMockService()) return;
2516 
2517         logd("testSatelliteModeRadiosWithAirplaneMode: start");
2518         InstrumentationRegistry.getInstrumentation().getUiAutomation()
2519                 .adoptShellPermissionIdentity(Manifest.permission.SATELLITE_COMMUNICATION,
2520                         Manifest.permission.WRITE_SECURE_SETTINGS,
2521                         Manifest.permission.NETWORK_SETTINGS,
2522                         Manifest.permission.ACCESS_FINE_LOCATION,
2523                         Manifest.permission.READ_PRIVILEGED_PHONE_STATE,
2524                         Manifest.permission.UWB_PRIVILEGED);
2525         assertTrue(isSatelliteProvisioned());
2526 
2527         ServiceStateRadioStateListener callback = new ServiceStateRadioStateListener(
2528                 sTelephonyManager.getServiceState(), sTelephonyManager.getRadioPowerState());
2529         sTelephonyManager.registerTelephonyCallback(Runnable::run, callback);
2530         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
2531         sSatelliteManager.registerForModemStateChanged(
2532                 getContext().getMainExecutor(), stateCallback);
2533         assertTrue(stateCallback.waitUntilResult(1));
2534 
2535         boolean originalEnabledState = isSatelliteEnabled();
2536         if (originalEnabledState) {
2537             requestSatelliteEnabled(false);
2538             assertTrue(stateCallback.waitUntilModemOff());
2539             assertFalse(isSatelliteEnabled());
2540             stateCallback.clearModemStates();
2541         }
2542 
2543         ConnectivityManager connectivityManager =
2544                 getContext().getSystemService(ConnectivityManager.class);
2545 
2546         // Get original satellite mode radios and original airplane mode
2547         String originalSatelliteModeRadios =  Settings.Global.getString(
2548                 getContext().getContentResolver(), Settings.Global.SATELLITE_MODE_RADIOS);
2549         logd("originalSatelliteModeRadios: " + originalSatelliteModeRadios);
2550         boolean originalAirplaneMode = Settings.Global.getInt(
2551                 getContext().getContentResolver(), Settings.Global.AIRPLANE_MODE_ON) != 0;
2552         SatelliteModeRadiosUpdater satelliteModeRadiosUpdater =
2553                 new SatelliteModeRadiosUpdater(getContext());
2554 
2555         try {
2556             identifyRadiosSensitiveToSatelliteMode();
2557             mTestSatelliteModeRadios = "";
2558             logd("test satelliteModeRadios: " + mTestSatelliteModeRadios);
2559             assertTrue(satelliteModeRadiosUpdater.setSatelliteModeRadios(mTestSatelliteModeRadios));
2560 
2561             // Enable Satellite and check whether all radios are disabled
2562             requestSatelliteEnabled(true, EXTERNAL_DEPENDENT_TIMEOUT);
2563             assertTrue(stateCallback.waitUntilResult(1));
2564             assertTrue(isSatelliteEnabled());
2565             assertSatelliteEnabledInSettings(true);
2566             assertTrue(areAllRadiosDisabled());
2567 
2568             // Enable airplane mode, check whether all radios are disabled and
2569             // also satellite mode is disabled
2570             connectivityManager.setAirplaneMode(true);
2571             // Wait for telephony radio power off
2572             callback.waitForRadioStateIntent(TelephonyManager.RADIO_POWER_OFF);
2573             // Wait for satellite mode state changed
2574             assertTrue(stateCallback.waitUntilResult(1));
2575             assertFalse(isSatelliteEnabled());
2576             assertSatelliteEnabledInSettings(false);
2577             assertTrue(areAllRadiosDisabled());
2578 
2579             // Disable airplane mode, check whether all radios are set to their initial state
2580             setRadioExpectedState();
2581             connectivityManager.setAirplaneMode(false);
2582             callback.waitForRadioStateIntent(TelephonyManager.RADIO_POWER_ON);
2583             assertTrue(areAllRadiosResetToInitialState());
2584         } finally {
2585             // Restore original satellite mode radios
2586             logd("restore original satellite mode radios and original airplane mode");
2587             connectivityManager.setAirplaneMode(originalAirplaneMode);
2588             callback.waitForRadioStateIntent(originalAirplaneMode
2589                     ? TelephonyManager.RADIO_POWER_OFF : TelephonyManager.RADIO_POWER_ON);
2590             assertTrue(satelliteModeRadiosUpdater.setSatelliteModeRadios(
2591                     originalSatelliteModeRadios));
2592             sTelephonyManager.unregisterTelephonyCallback(callback);
2593             sSatelliteManager.unregisterForModemStateChanged(stateCallback);
2594             unregisterSatelliteModeRadios();
2595             InstrumentationRegistry.getInstrumentation().getUiAutomation()
2596                     .dropShellPermissionIdentity();
2597         }
2598     }
2599 
2600     @Test
testSendSatelliteDatagram_DemoMode_not_Aligned()2601     public void testSendSatelliteDatagram_DemoMode_not_Aligned() {
2602         if (!shouldTestSatelliteWithMockService()) return;
2603 
2604         logd("testSendSatelliteDatagram_DemoMode_not_Aligned");
2605         grantSatellitePermission();
2606         assertTrue(isSatelliteProvisioned());
2607 
2608         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
2609         sSatelliteManager.registerForModemStateChanged(
2610                 getContext().getMainExecutor(), stateCallback);
2611         assertTrue(stateCallback.waitUntilResult(1));
2612         assertTrue(sMockSatelliteServiceManager.setShouldSendDatagramToModemInDemoMode(true));
2613         assertTrue(sMockSatelliteServiceManager.overrideSatellitePointingUiClassName());
2614         // Enable satellite with demo mode on
2615         if (isSatelliteEnabled()) {
2616             requestSatelliteEnabled(false);
2617             assertTrue(stateCallback.waitUntilModemOff());
2618             stateCallback.clearModemStates();
2619         }
2620         requestSatelliteEnabledForDemoMode(true);
2621         assertTrue(stateCallback.waitUntilResult(2));
2622         assertTrue(isSatelliteEnabled());
2623         assertTrue(getIsEmergency());
2624 
2625         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
2626         SatelliteTransmissionUpdateCallbackTest callback =
2627                 new SatelliteTransmissionUpdateCallbackTest();
2628         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
2629                 resultListener::offer, callback);
2630         Integer errorCode;
2631         try {
2632             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2633         } catch (InterruptedException ex) {
2634             fail("testSendSatelliteDatagram_DemoMode_not_Aligned: Got InterruptedException in "
2635                     + "waiting for the startSatelliteTransmissionUpdates result code");
2636             return;
2637         }
2638         assertNotNull(errorCode);
2639         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
2640 
2641         // Send satellite datagram and satellite is not aligned.
2642         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(false,
2643                 DatagramController.TIMEOUT_TYPE_ALIGN, TEST_SATELLITE_DEVICE_ALIGN_TIMEOUT_MILLIS));
2644         String mText = "This is a test datagram message from user";
2645         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
2646         callback.clearSendDatagramStateChanges();
2647         sSatelliteManager.setDeviceAlignedWithSatellite(false);
2648         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
2649                 datagram, true, getContext().getMainExecutor(),
2650                 resultListener::offer);
2651 
2652         try {
2653             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2654         } catch (InterruptedException ex) {
2655             fail("testSendSatelliteDatagram_DemoMode_not_Aligned: Got InterruptedException in"
2656                     + " waiting for the sendDatagram result code");
2657             return;
2658         }
2659         assertNotNull(errorCode);
2660         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_NOT_REACHABLE);
2661 
2662         /*
2663          * Send datagram transfer state should have the following transitions:
2664          * 1) IDLE to SENDING
2665          * 2) SENDING to SENDING_FAILED
2666          * 3) SENDING_FAILED to IDLE
2667          */
2668         assertTrue(callback.waitUntilOnSendDatagramStateChanged(3));
2669         assertThat(callback.getNumOfSendDatagramStateChanges()).isEqualTo(3);
2670         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
2671                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2672                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
2673                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2674         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
2675                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2676                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
2677                         0, SatelliteManager.SATELLITE_RESULT_NOT_REACHABLE));
2678         assertThat(callback.getSendDatagramStateChange(2)).isEqualTo(
2679                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2680                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
2681                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2682 
2683         // Move to sending state and wait for satellite alignment forever
2684         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(false,
2685                 DatagramController.TIMEOUT_TYPE_ALIGN,
2686                 TEST_SATELLITE_DEVICE_ALIGN_FOREVER_TIMEOUT_MILLIS));
2687         callback.clearSendDatagramStateChanges();
2688         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
2689         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
2690                 datagram, true, getContext().getMainExecutor(),
2691                 resultListener::offer);
2692 
2693         // No response for the request sendDatagram received
2694         try {
2695             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2696         } catch (InterruptedException ex) {
2697             fail("testSendSatelliteDatagram_DemoMode_not_Aligned: Got InterruptedException in"
2698                     + " waiting for the sendDatagram result code");
2699             return;
2700         }
2701         assertNull(errorCode);
2702 
2703         /*
2704          * Send datagram transfer state should have the following transitions:
2705          * 1) IDLE to SENDING
2706          */
2707         assertTrue(callback.waitUntilOnSendDatagramStateChanged(1));
2708         assertThat(callback.getNumOfSendDatagramStateChanges()).isEqualTo(1);
2709         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
2710                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2711                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
2712                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2713 
2714         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
2715         callback.clearSendDatagramStateChanges();
2716         sSatelliteManager.setDeviceAlignedWithSatellite(true);
2717 
2718         // Satellite is aligned now. We should get the response of the request
2719         // sendSatelliteDatagrams.
2720         try {
2721             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2722         } catch (InterruptedException ex) {
2723             fail("testSendSatelliteDatagram_DemoMode_not_Aligned: Got InterruptedException in"
2724                     + " waiting for the sendDatagram result code");
2725             return;
2726         }
2727         assertNotNull(errorCode);
2728         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
2729 
2730         /*
2731          * Send datagram transfer state should have the following transitions:
2732          * 1) SENDING to SEND_SUCCESS
2733          * 2) SEND_SUCCESS to IDLE
2734          */
2735         assertTrue(callback.waitUntilOnSendDatagramStateChanged(2));
2736         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
2737                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2738                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
2739                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2740         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
2741                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2742                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
2743                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2744 
2745         // Move to sending state and wait for satellite alignment forever again
2746         sSatelliteManager.setDeviceAlignedWithSatellite(false);
2747         callback.clearSendDatagramStateChanges();
2748         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
2749                 datagram, true, getContext().getMainExecutor(),
2750                 resultListener::offer);
2751 
2752         // No response for the request sendDatagram received
2753         try {
2754             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2755         } catch (InterruptedException ex) {
2756             fail("testSendSatelliteDatagram_DemoMode_not_Aligned: Got InterruptedException in"
2757                     + " waiting for the sendDatagram result code");
2758             return;
2759         }
2760         assertNull(errorCode);
2761 
2762         /*
2763          * Send datagram transfer state should have the following transitions:
2764          * 1) IDLE to SENDING
2765          */
2766         assertTrue(callback.waitUntilOnSendDatagramStateChanged(1));
2767         assertThat(callback.getNumOfSendDatagramStateChanges()).isEqualTo(1);
2768         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
2769                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2770                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
2771                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2772 
2773         callback.clearSendDatagramStateChanges();
2774         stateCallback.clearModemStates();
2775         requestSatelliteEnabled(false);
2776         assertTrue(stateCallback.waitUntilModemOff());
2777         stateCallback.clearModemStates();
2778 
2779         try {
2780             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2781         } catch (InterruptedException ex) {
2782             fail("testSendSatelliteDatagram_DemoMode_not_Aligned: Got InterruptedException in"
2783                     + " waiting for the sendDatagram result code");
2784             return;
2785         }
2786         assertNotNull(errorCode);
2787         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_REQUEST_ABORTED);
2788 
2789         /*
2790          * Send datagram transfer state should have the following transitions:
2791          * 1) SENDING to SENDING_FAILED
2792          * 2) SENDING_FAILED to IDLE
2793          */
2794         assertTrue(callback.waitUntilOnSendDatagramStateChanged(2));
2795         assertThat(callback.getNumOfSendDatagramStateChanges()).isEqualTo(2);
2796         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
2797                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2798                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
2799                         1, SatelliteManager.SATELLITE_RESULT_REQUEST_ABORTED));
2800         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
2801                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2802                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
2803                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2804 
2805         callback.clearSendDatagramStateChanges();
2806         sSatelliteManager.stopTransmissionUpdates(callback, getContext().getMainExecutor(),
2807                 resultListener::offer);
2808 
2809         // Restore satellite device align time out to default value.
2810         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(true,
2811                 DatagramController.TIMEOUT_TYPE_ALIGN, 0));
2812         assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
2813         sSatelliteManager.unregisterForModemStateChanged(stateCallback);
2814         revokeSatellitePermission();
2815     }
2816 
2817     @Test
testReceiveSatelliteDatagram_DemoMode_not_Aligned()2818     public void testReceiveSatelliteDatagram_DemoMode_not_Aligned() {
2819         if (!shouldTestSatelliteWithMockService()) return;
2820 
2821         logd("testReceiveSatelliteDatagram_DemoMode_not_Aligned");
2822         grantSatellitePermission();
2823         assertTrue(isSatelliteProvisioned());
2824 
2825         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
2826         sSatelliteManager.registerForModemStateChanged(
2827                 getContext().getMainExecutor(), stateCallback);
2828         assertTrue(stateCallback.waitUntilResult(1));
2829         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
2830                 startTransmissionUpdates();
2831         assertTrue(sMockSatelliteServiceManager.overrideSatellitePointingUiClassName());
2832 
2833         // Request enable satellite with demo mode on
2834         if (isSatelliteEnabled()) {
2835             requestSatelliteEnabled(false);
2836             assertTrue(stateCallback.waitUntilModemOff());
2837             stateCallback.clearModemStates();
2838         }
2839         requestSatelliteEnabledForDemoMode(true);
2840         assertTrue(stateCallback.waitUntilResult(2));
2841         assertTrue(isSatelliteEnabled());
2842         assertTrue(getIsEmergency());
2843 
2844         sSatelliteManager.setDeviceAlignedWithSatellite(true);
2845         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(false,
2846                 DatagramController.TIMEOUT_TYPE_DATAGRAM_DELAY_IN_DEMO_MODE,
2847                 TEST_DATAGRAM_DELAY_IN_DEMO_MODE_TIMEOUT_LONG_MILLIS));
2848 
2849         // Send satellite datagram to compare with the received datagram in demo mode
2850         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
2851         String mText = "This is a test datagram message";
2852         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
2853         sSatelliteManager.sendDatagram(
2854                 SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE, datagram, true,
2855                 getContext().getMainExecutor(), resultListener::offer);
2856 
2857         Integer errorCode;
2858         try {
2859             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2860         } catch (InterruptedException ex) {
2861             fail("testReceiveSatelliteDatagram_DemoMode_not_Aligned: Got InterruptedException in "
2862                     + "waiting for the sendDatagram result code");
2863             return;
2864         }
2865         assertNotNull(errorCode);
2866         Log.d(TAG, "testReceiveSatelliteDatagram_DemoMode_not_Aligned: sendDatagram "
2867                 + "errorCode=" + errorCode);
2868 
2869         // Test poll pending satellite datagram for demo mode while it is not aligned
2870         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
2871         sSatelliteManager.setDeviceAlignedWithSatellite(false);
2872         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(false,
2873                 DatagramController.TIMEOUT_TYPE_ALIGN, TEST_SATELLITE_DEVICE_ALIGN_TIMEOUT_MILLIS));
2874 
2875         // Datagram transfer state should change from RECEIVING to IDLE.
2876         assertTrue(transmissionUpdateCallback
2877                 .waitUntilOnReceiveDatagramStateChanged(3));
2878         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
2879                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2880                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVING,
2881                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2882         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(1)).isEqualTo(
2883                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2884                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_FAILED,
2885                         0, SatelliteManager.SATELLITE_RESULT_NOT_REACHABLE));
2886         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(2)).isEqualTo(
2887                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
2888                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
2889                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
2890 
2891         requestSatelliteEnabled(false);
2892         assertTrue(stateCallback.waitUntilModemOff());
2893         stopTransmissionUpdates(transmissionUpdateCallback);
2894         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(true,
2895                 DatagramController.TIMEOUT_TYPE_ALIGN, 0));
2896         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(true,
2897                 DatagramController.TIMEOUT_TYPE_DATAGRAM_DELAY_IN_DEMO_MODE, 0));
2898         assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
2899         sSatelliteManager.unregisterForModemStateChanged(stateCallback);
2900         revokeSatellitePermission();
2901     }
2902 
2903     @Test
testSatelliteModemBusy_modemSendingDatagram_pollingFailure()2904     public void testSatelliteModemBusy_modemSendingDatagram_pollingFailure() {
2905         if (!shouldTestSatelliteWithMockService()) return;
2906 
2907         logd("testSatelliteModemBusy_modemSendingDatagram_pollingFailure");
2908         grantSatellitePermission();
2909         assertTrue(isSatelliteProvisioned());
2910 
2911         String mText = "This is a test datagram message from user";
2912         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
2913         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
2914 
2915         // Wait to process datagrams so that datagrams are added to pending list
2916         // and modem is busy sending datagrams
2917         sMockSatelliteServiceManager.setWaitToSend(true);
2918 
2919         LinkedBlockingQueue<Integer> sendResultListener = new LinkedBlockingQueue<>(1);
2920         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
2921                 datagram, true, getContext().getMainExecutor(),
2922                 sendResultListener::offer);
2923 
2924         LinkedBlockingQueue<Integer> pollResultListener = new LinkedBlockingQueue<>(1);
2925         sSatelliteManager.pollPendingDatagrams(getContext().getMainExecutor(),
2926                 pollResultListener::offer);
2927 
2928         Integer errorCode;
2929         try {
2930             errorCode = pollResultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2931         } catch (InterruptedException ex) {
2932             fail("testSatelliteModemBusy_modemSendingDatagram_pollingFailure: Got "
2933                     + "InterruptedException in waiting for the pollPendingDatagrams "
2934                     + "result code");
2935             return;
2936         }
2937         assertNotNull(errorCode);
2938         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_MODEM_BUSY);
2939 
2940         // Send datagram successfully to bring sending state back to IDLE.
2941         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
2942         assertTrue(sMockSatelliteServiceManager.sendSavedDatagram());
2943         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
2944         sMockSatelliteServiceManager.setWaitToSend(false);
2945         revokeSatellitePermission();
2946     }
2947 
2948     @Test
testSatelliteModemBusy_modemPollingDatagrams_pollingFailure()2949     public void testSatelliteModemBusy_modemPollingDatagrams_pollingFailure() {
2950         if (!shouldTestSatelliteWithMockService()) return;
2951 
2952         logd("testSatelliteModemBusy_modemPollingDatagrams_pollingFailure");
2953         grantSatellitePermission();
2954         assertTrue(isSatelliteProvisioned());
2955 
2956         LinkedBlockingQueue<Integer> pollResultListener1 = new LinkedBlockingQueue<>(1);
2957         sSatelliteManager.pollPendingDatagrams(getContext().getMainExecutor(),
2958                 pollResultListener1::offer);
2959 
2960         // As we already got one polling request, this second polling request would fail
2961         LinkedBlockingQueue<Integer> pollResultListener2 = new LinkedBlockingQueue<>(1);
2962         sSatelliteManager.pollPendingDatagrams(getContext().getMainExecutor(),
2963                 pollResultListener2::offer);
2964 
2965         Integer errorCode;
2966         try {
2967             errorCode = pollResultListener2.poll(TIMEOUT, TimeUnit.MILLISECONDS);
2968         } catch (InterruptedException ex) {
2969             fail("testSatelliteModemBusy_modemSendingDatagram_pollingFailure: Got "
2970                     + "InterruptedException in waiting for the pollPendingDatagrams "
2971                     + "result code");
2972             return;
2973         }
2974         assertNotNull(errorCode);
2975         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_MODEM_BUSY);
2976 
2977         // Receive one datagram successfully to bring receiving state back to IDLE.
2978         String receivedText = "This is a test datagram message from satellite";
2979         android.telephony.satellite.stub.SatelliteDatagram receivedDatagram =
2980                 new android.telephony.satellite.stub.SatelliteDatagram();
2981         receivedDatagram.data = receivedText.getBytes();
2982         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 0);
2983         revokeSatellitePermission();
2984     }
2985 
2986     @Test
testSatelliteModemBusy_modemPollingDatagram_sendingDelayed()2987     public void testSatelliteModemBusy_modemPollingDatagram_sendingDelayed() {
2988         if (!shouldTestSatelliteWithMockService()) return;
2989 
2990         logd("testSatelliteModemBusy_modemPollingDatagram_sendingDelayed");
2991         grantSatellitePermission();
2992         assertTrue(isSatelliteProvisioned());
2993 
2994         String mText = "This is a test datagram message from user";
2995         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
2996         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
2997 
2998         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
2999         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
3000                 new SatelliteTransmissionUpdateCallbackTest();
3001         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
3002                 resultListener::offer, transmissionUpdateCallback);
3003         Integer errorCode;
3004         try {
3005             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
3006         } catch (InterruptedException ex) {
3007             fail("testSatelliteModemBusy_modemPollingDatagram_sendingDelayed: "
3008                     + "Got InterruptedException in waiting for the "
3009                     + "startSatelliteTransmissionUpdates result code");
3010             return;
3011         }
3012         assertNotNull(errorCode);
3013         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
3014 
3015         SatelliteDatagramCallbackTest satelliteDatagramCallback =
3016                 new SatelliteDatagramCallbackTest();
3017         sSatelliteManager.registerForIncomingDatagram(
3018                 getContext().getMainExecutor(), satelliteDatagramCallback);
3019 
3020         transmissionUpdateCallback.clearSendDatagramStateChanges();
3021         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
3022 
3023         LinkedBlockingQueue<Integer> pollResultListener = new LinkedBlockingQueue<>(1);
3024         sSatelliteManager.pollPendingDatagrams(getContext().getMainExecutor(),
3025                 pollResultListener::offer);
3026         // Datagram transfer state changes from IDLE -> RECEIVING.
3027         assertSingleReceiveDatagramStateChanged(transmissionUpdateCallback,
3028                 SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVING,
3029                 0, SatelliteManager.SATELLITE_RESULT_SUCCESS);
3030 
3031         LinkedBlockingQueue<Integer> sendResultListener = new LinkedBlockingQueue<>(1);
3032         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
3033                 datagram, true, getContext().getMainExecutor(),
3034                 sendResultListener::offer);
3035         // Sending datagram will be delayed as modem is in RECEIVING state
3036         assertFalse(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
3037 
3038         String receivedText = "This is a test datagram message from satellite";
3039         android.telephony.satellite.stub.SatelliteDatagram receivedDatagram =
3040                 new android.telephony.satellite.stub.SatelliteDatagram();
3041         receivedDatagram.data = receivedText.getBytes();
3042         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
3043         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 0);
3044         // As pending count is 0, datagram transfer state changes from
3045         // RECEIVING -> RECEIVE_SUCCESS -> IDLE.
3046         int expectedNumOfEvents = 2;
3047         assertTrue(transmissionUpdateCallback
3048                 .waitUntilOnReceiveDatagramStateChanged(expectedNumOfEvents));
3049         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
3050                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3051                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_SUCCESS,
3052                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3053         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(1)).isEqualTo(
3054                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3055                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
3056                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3057 
3058         // As polling is completed, now modem will start sending datagrams
3059         expectedNumOfEvents = 3;
3060         assertTrue(transmissionUpdateCallback.
3061                 waitUntilOnSendDatagramStateChanged(expectedNumOfEvents));
3062         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(0)).isEqualTo(
3063                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3064                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
3065                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3066         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(1)).isEqualTo(
3067                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3068                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
3069                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3070         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(2)).isEqualTo(
3071                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3072                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
3073                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3074 
3075         transmissionUpdateCallback.clearSendDatagramStateChanges();
3076         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
3077         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
3078         sSatelliteManager.stopTransmissionUpdates(transmissionUpdateCallback,
3079                 getContext().getMainExecutor(), resultListener::offer);
3080         sSatelliteManager.unregisterForIncomingDatagram(satelliteDatagramCallback);
3081         revokeSatellitePermission();
3082     }
3083 
3084     @Test
testRebindToSatelliteService()3085     public void testRebindToSatelliteService() {
3086         if (!shouldTestSatelliteWithMockService()) return;
3087 
3088         grantSatellitePermission();
3089         assertTrue(isSatelliteSupported());
3090 
3091         assertTrue(sMockSatelliteServiceManager.connectExternalSatelliteService());
3092         assertTrue(sMockSatelliteServiceManager.waitForRemoteSatelliteServiceConnected(1));
3093 
3094         // Forcefully stop the external satellite service.
3095         assertTrue(sMockSatelliteServiceManager.stopExternalSatelliteService());
3096         assertTrue(sMockSatelliteServiceManager
3097                 .waitForExternalSatelliteServiceDisconnected(1));
3098 
3099         // Reconnect CTS to the external satellite service.
3100         assertTrue(sMockSatelliteServiceManager.setupExternalSatelliteService());
3101         // Telephony should rebind to the external satellite service after the binding died.
3102         assertTrue(sMockSatelliteServiceManager.waitForRemoteSatelliteServiceConnected(1));
3103 
3104         // Restore original binding states
3105         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
3106         long registerResult = sSatelliteManager.registerForModemStateChanged(
3107                 getContext().getMainExecutor(), callback);
3108         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
3109         assertTrue(callback.waitUntilResult(1));
3110 
3111         callback.clearModemStates();
3112         sMockSatelliteServiceManager.resetSatelliteService();
3113         assertTrue(sMockSatelliteServiceManager.connectSatelliteService());
3114         assertTrue(callback.waitUntilModemOff(EXTERNAL_DEPENDENT_TIMEOUT));
3115         callback.clearModemStates();
3116 
3117         requestSatelliteEnabled(true);
3118         assertTrue(callback.waitUntilResult(2));
3119         assertEquals(2, callback.getTotalCountOfModemStates());
3120         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
3121                 callback.getModemState(0));
3122         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.getModemState(1));
3123         assertTrue(isSatelliteEnabled());
3124 
3125         assertTrue(sMockSatelliteServiceManager.stopExternalSatelliteService());
3126         assertTrue(sMockSatelliteServiceManager
3127                 .waitForExternalSatelliteServiceDisconnected(1));
3128 
3129         revokeSatellitePermission();
3130     }
3131 
3132     @Test
testRebindToSatelliteGatewayService()3133     public void testRebindToSatelliteGatewayService() {
3134         if (!shouldTestSatelliteWithMockService()) return;
3135 
3136         grantSatellitePermission();
3137         assertTrue(isSatelliteProvisioned());
3138 
3139         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
3140         long registerResult = sSatelliteManager.registerForModemStateChanged(
3141                 getContext().getMainExecutor(), callback);
3142         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
3143         assertTrue(callback.waitUntilResult(1));
3144 
3145         if (isSatelliteEnabled()) {
3146             callback.clearModemStates();
3147             requestSatelliteEnabled(false);
3148             assertTrue(callback.waitUntilResult(2));
3149             assertEquals(2, callback.getTotalCountOfModemStates());
3150             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DISABLING_SATELLITE,
3151                     callback.getModemState(0));
3152             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.getModemState(1));
3153             assertFalse(isSatelliteEnabled());
3154         }
3155 
3156         assertTrue(sMockSatelliteServiceManager.connectExternalSatelliteGatewayService());
3157         callback.clearModemStates();
3158         requestSatelliteEnabled(true);
3159         assertTrue(callback.waitUntilResult(2));
3160         assertEquals(2, callback.getTotalCountOfModemStates());
3161         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
3162                 callback.getModemState(0));
3163         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.getModemState(1));
3164         assertTrue(isSatelliteEnabled());
3165         assertTrue(sMockSatelliteServiceManager.waitForRemoteSatelliteGatewayServiceConnected(1));
3166 
3167         // Forcefully stop the external satellite gateway service.
3168         assertTrue(sMockSatelliteServiceManager.stopExternalSatelliteGatewayService());
3169         assertTrue(sMockSatelliteServiceManager
3170                 .waitForExternalSatelliteGatewayServiceDisconnected(1));
3171 
3172         // Reconnect CTS to the external satellite gateway service.
3173         assertTrue(sMockSatelliteServiceManager.setupExternalSatelliteGatewayService());
3174         // Telephony should rebind to the external satellite gateway service after the binding died.
3175         assertTrue(sMockSatelliteServiceManager.waitForRemoteSatelliteGatewayServiceConnected(1));
3176 
3177         sSatelliteManager.unregisterForModemStateChanged(callback);
3178         assertTrue(sMockSatelliteServiceManager.restoreSatelliteGatewayServicePackageName());
3179 
3180         revokeSatellitePermission();
3181     }
3182 
3183     @Test
testSatelliteAttachEnabledForCarrier()3184     public void testSatelliteAttachEnabledForCarrier() {
3185         if (!shouldTestSatelliteWithMockService() || !Flags.carrierEnabledSatelliteFlag()) return;
3186 
3187         logd("testSatelliteAttachEnabledForCarrier");
3188         grantSatellitePermission();
3189         beforeSatelliteForCarrierTest();
3190         @SatelliteManager.SatelliteResult int expectedSuccess =
3191                 SatelliteManager.SATELLITE_RESULT_SUCCESS;
3192         @SatelliteManager.SatelliteResult int expectedError;
3193 
3194         /* Test when satellite is not supported in the carrier config */
3195         PersistableBundle bundle = new PersistableBundle();
3196         bundle.putBoolean(
3197                 CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, false);
3198 
3199         overrideCarrierConfig(sTestSubIDForCarrierSatellite, bundle);
3200         requestSatelliteAttachEnabledForCarrier(true, SatelliteManager.SATELLITE_RESULT_SUCCESS);
3201 
3202         Pair<Boolean, Integer> pair = requestIsSatelliteAttachEnabledForCarrier();
3203         assertEquals(true, pair.first.booleanValue());
3204         assertNull(pair.second);
3205 
3206 
3207         /* Test when satellite is supported in the carrier config */
3208         setSatelliteError(expectedSuccess);
3209         bundle = new PersistableBundle();
3210         bundle.putBoolean(
3211                 CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
3212         PersistableBundle plmnBundle = new PersistableBundle();
3213         int[] intArray1 = {3, 5};
3214         int[] intArray2 = {3};
3215         plmnBundle.putIntArray("123411", intArray1);
3216         plmnBundle.putIntArray("123412", intArray2);
3217         bundle.putPersistableBundle(
3218                 CarrierConfigManager.KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
3219                 plmnBundle);
3220         overrideCarrierConfig(sTestSubIDForCarrierSatellite, bundle);
3221 
3222         ArrayList<String> expectedCarrierPlmnList = new ArrayList<>();
3223         expectedCarrierPlmnList.add("123411");
3224         expectedCarrierPlmnList.add("123412");
3225         assertTrue(sMockSatelliteServiceManager.waitForEventOnSetSatellitePlmn(1));
3226         List<String> carrierPlmnList = sMockSatelliteServiceManager.getCarrierPlmnList();
3227         assertNotNull(carrierPlmnList);
3228         assertEquals(expectedCarrierPlmnList, carrierPlmnList);
3229         List<String> satellitePlmnListFromOverlayConfig =
3230                 sMockSatelliteServiceManager.getPlmnListFromOverlayConfig();
3231         List<String> expectedAllSatellitePlmnList = SatelliteServiceUtils.mergeStrLists(
3232                 carrierPlmnList, satellitePlmnListFromOverlayConfig);
3233         List<String> allSatellitePlmnList = sMockSatelliteServiceManager.getAllSatellitePlmnList();
3234         assertNotNull(allSatellitePlmnList);
3235         assertEquals(expectedAllSatellitePlmnList, allSatellitePlmnList);
3236         requestSatelliteAttachEnabledForCarrier(true, expectedSuccess);
3237 
3238         pair = requestIsSatelliteAttachEnabledForCarrier();
3239         assertEquals(true, pair.first.booleanValue());
3240         assertNull(pair.second);
3241 
3242         /* Test when satellite is supported, and requested satellite disabled */
3243         requestSatelliteAttachEnabledForCarrier(false, expectedSuccess);
3244         assertEquals(false, getIsSatelliteEnabledForCarrierFromMockService());
3245         pair = requestIsSatelliteAttachEnabledForCarrier();
3246         assertEquals(false, pair.first.booleanValue());
3247         assertNull(pair.second);
3248 
3249         /* Test when satellite is supported, but modem returns INVALID_MODEM_STATE */
3250         expectedError = SatelliteManager.SATELLITE_RESULT_INVALID_MODEM_STATE;
3251         setSatelliteError(expectedError);
3252         requestSatelliteAttachEnabledForCarrier(true, expectedError);
3253 
3254         pair = requestIsSatelliteAttachEnabledForCarrier();
3255         assertEquals(true, pair.first.booleanValue());
3256         assertNull(pair.second);
3257 
3258         /* Test when satellite is supported, and requested satellite disabled */
3259         expectedError = SatelliteManager.SATELLITE_RESULT_SUCCESS;
3260         requestSatelliteAttachEnabledForCarrier(false, expectedError);
3261         assertEquals(false, getIsSatelliteEnabledForCarrierFromMockService());
3262         pair = requestIsSatelliteAttachEnabledForCarrier();
3263         assertEquals(false, pair.first.booleanValue());
3264         assertNull(pair.second);
3265 
3266         /* Test when satellite is supported, but modem returns RADIO_NOT_AVAILABLE */
3267         expectedError = SatelliteManager.SATELLITE_RESULT_RADIO_NOT_AVAILABLE;
3268         setSatelliteError(expectedError);
3269         requestSatelliteAttachEnabledForCarrier(true, expectedError);
3270 
3271         pair = requestIsSatelliteAttachEnabledForCarrier();
3272         assertEquals(true, pair.first.booleanValue());
3273         assertNull(pair.second);
3274 
3275         afterSatelliteForCarrierTest();
3276         revokeSatellitePermission();
3277     }
3278 
3279     @Test
testSatelliteAttachRestrictionForCarrier()3280     public void testSatelliteAttachRestrictionForCarrier() {
3281         if (!shouldTestSatelliteWithMockService() || !Flags.carrierEnabledSatelliteFlag()) return;
3282 
3283         logd("testSatelliteAttachRestrictionForCarrier");
3284         grantSatellitePermission();
3285         beforeSatelliteForCarrierTest();
3286         clearSatelliteEnabledForCarrier();
3287         @SatelliteManager.SatelliteResult int expectedSuccess =
3288                 SatelliteManager.SATELLITE_RESULT_SUCCESS;
3289 
3290         /* Test when satellite is supported but there is a restriction reason */
3291         setSatelliteError(expectedSuccess);
3292         PersistableBundle bundle = new PersistableBundle();
3293         bundle.putBoolean(
3294                 CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
3295         overrideCarrierConfig(sTestSubIDForCarrierSatellite, bundle);
3296         int restrictionReason = SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION;
3297         requestAddSatelliteAttachRestrictionForCarrier(restrictionReason,
3298                 SatelliteManager.SATELLITE_RESULT_SUCCESS);
3299         verifySatelliteAttachRestrictionForCarrier(restrictionReason, true);
3300         requestSatelliteAttachEnabledForCarrier(true, expectedSuccess);
3301         Pair<Boolean, Integer> pair = requestIsSatelliteAttachEnabledForCarrier();
3302         assertEquals(true, pair.first.booleanValue());
3303         assertNull(pair.second);
3304         assertEquals(false, getIsSatelliteEnabledForCarrierFromMockService());
3305 
3306         /* If the restriction reason 'GEOLOCATION' is removed and the restriction reason is
3307            empty, re-evaluate and trigger enable/disable again */
3308         requestRemoveSatelliteAttachRestrictionForCarrier(restrictionReason,
3309                 SatelliteManager.SATELLITE_RESULT_SUCCESS);
3310         verifySatelliteAttachRestrictionForCarrier(restrictionReason, false);
3311         assertEquals(true, getIsSatelliteEnabledForCarrierFromMockService());
3312 
3313         /* If the restriction reason 'GEOLOCATION' is added and the restriction reason becomes
3314            'GEOLOCATION', re-evaluate and trigger enable/disable again */
3315         requestAddSatelliteAttachRestrictionForCarrier(restrictionReason,
3316                 SatelliteManager.SATELLITE_RESULT_SUCCESS);
3317         verifySatelliteAttachRestrictionForCarrier(restrictionReason, true);
3318         assertEquals(false, getIsSatelliteEnabledForCarrierFromMockService());
3319 
3320         /* If the restriction reason 'ENTITLEMENT' is added and the restriction reasons become
3321            ‘GEOLOCATION’ and ‘ENTITLEMENT.’ re-evaluate and trigger enable/disable again */
3322         restrictionReason = SATELLITE_COMMUNICATION_RESTRICTION_REASON_ENTITLEMENT;
3323         requestAddSatelliteAttachRestrictionForCarrier(restrictionReason,
3324                 SatelliteManager.SATELLITE_RESULT_SUCCESS);
3325         verifySatelliteAttachRestrictionForCarrier(restrictionReason, true);
3326         assertEquals(false, getIsSatelliteEnabledForCarrierFromMockService());
3327 
3328         /* If the restriction reason 'ENTITLEMENT' is removed and the restriction reason becomes
3329            ‘GEOLOCATION’, re-evaluate and trigger enable/disable again */
3330         requestRemoveSatelliteAttachRestrictionForCarrier(restrictionReason,
3331                 SatelliteManager.SATELLITE_RESULT_SUCCESS);
3332         restrictionReason = SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION;
3333         verifySatelliteAttachRestrictionForCarrier(restrictionReason, true);
3334         assertEquals(false, getIsSatelliteEnabledForCarrierFromMockService());
3335 
3336         /* If the restriction reason 'GEOLOCATION' is removed and the restriction reason becomes
3337             empty, re-evaluate and trigger enable/disable again */
3338         requestRemoveSatelliteAttachRestrictionForCarrier(restrictionReason,
3339                 SatelliteManager.SATELLITE_RESULT_SUCCESS);
3340         verifySatelliteAttachRestrictionForCarrier(restrictionReason, false);
3341         assertEquals(true, getIsSatelliteEnabledForCarrierFromMockService());
3342 
3343         afterSatelliteForCarrierTest();
3344         revokeSatellitePermission();
3345     }
3346 
3347     @Test
3348     @RequiresFlagsEnabled(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
testNtnSignalStrength()3349     public void testNtnSignalStrength() {
3350         if (!shouldTestSatelliteWithMockService()) return;
3351 
3352         logd("testNtnSignalStrength: start");
3353         grantSatellitePermission();
3354 
3355         NtnSignalStrengthCallbackTest ntnSignalStrengthCallbackTest =
3356                 new NtnSignalStrengthCallbackTest();
3357 
3358         /* register callback for non-terrestrial network signal strength changed event */
3359         sSatelliteManager.registerForNtnSignalStrengthChanged(getContext().getMainExecutor(),
3360                 ntnSignalStrengthCallbackTest);
3361 
3362         @NtnSignalStrength.NtnSignalStrengthLevel int expectedLevel =
3363                 NtnSignalStrength.NTN_SIGNAL_STRENGTH_NONE;
3364         @SatelliteManager.SatelliteResult int expectedError;
3365         setSatelliteError(SatelliteManager.SATELLITE_RESULT_SUCCESS);
3366         setNtnSignalStrength(expectedLevel);
3367         Pair<NtnSignalStrength, Integer> pairResult = requestNtnSignalStrength();
3368         assertEquals(expectedLevel, pairResult.first.getLevel());
3369         assertNull(pairResult.second);
3370 
3371         expectedLevel = NtnSignalStrength.NTN_SIGNAL_STRENGTH_GOOD;
3372         expectedError = SatelliteManager.SATELLITE_RESULT_MODEM_ERROR;
3373         setSatelliteError(expectedError);
3374         setNtnSignalStrength(expectedLevel);
3375         pairResult = requestNtnSignalStrength();
3376         assertNull(pairResult.first);
3377         assertEquals(expectedError, pairResult.second.intValue());
3378 
3379         expectedLevel = NtnSignalStrength.NTN_SIGNAL_STRENGTH_GOOD;
3380         expectedError = SatelliteManager.SATELLITE_RESULT_SUCCESS;
3381         setSatelliteError(expectedError);
3382         setNtnSignalStrength(expectedLevel);
3383         pairResult = requestNtnSignalStrength();
3384         assertEquals(expectedLevel, pairResult.first.getLevel());
3385         assertNull(pairResult.second);
3386 
3387         /* As non-terrestrial network signal strength is cached in framework, simple set won't
3388         affect cached value */
3389         expectedLevel = NtnSignalStrength.NTN_SIGNAL_STRENGTH_GREAT;
3390         setNtnSignalStrength(expectedLevel);
3391         pairResult = requestNtnSignalStrength();
3392         assertNotEquals(expectedLevel, pairResult.first.getLevel());
3393         assertNull(pairResult.second);
3394 
3395         /* Cache will be updated when non-terrestrial network signal strength changed event comes */
3396         sendOnNtnSignalStrengthChanged(expectedLevel);
3397         assertTrue(ntnSignalStrengthCallbackTest.waitUntilResult(1));
3398         pairResult = requestNtnSignalStrength();
3399         assertEquals(expectedLevel, pairResult.first.getLevel());
3400         assertNull(pairResult.second);
3401         assertEquals(expectedLevel, ntnSignalStrengthCallbackTest.mNtnSignalStrength.getLevel());
3402 
3403         expectedLevel = NtnSignalStrength.NTN_SIGNAL_STRENGTH_MODERATE;
3404         sendOnNtnSignalStrengthChanged(expectedLevel);
3405         assertTrue(ntnSignalStrengthCallbackTest.waitUntilResult(1));
3406         pairResult = requestNtnSignalStrength();
3407         assertEquals(expectedLevel, pairResult.first.getLevel());
3408         assertNull(pairResult.second);
3409         assertEquals(expectedLevel, ntnSignalStrengthCallbackTest.mNtnSignalStrength.getLevel());
3410 
3411         /* Initialize the non-terrestrial signal strength cache in the framework */
3412         expectedLevel = NtnSignalStrength.NTN_SIGNAL_STRENGTH_NONE;
3413         sendOnNtnSignalStrengthChanged(expectedLevel);
3414         assertTrue(ntnSignalStrengthCallbackTest.waitUntilResult(1));
3415         pairResult = requestNtnSignalStrength();
3416         assertEquals(expectedLevel, pairResult.first.getLevel());
3417         assertNull(pairResult.second);
3418         assertEquals(expectedLevel, ntnSignalStrengthCallbackTest.mNtnSignalStrength.getLevel());
3419 
3420         /* unregister non-terrestrial network signal strength changed event callback */
3421         sSatelliteManager.unregisterForNtnSignalStrengthChanged(ntnSignalStrengthCallbackTest);
3422 
3423         revokeSatellitePermission();
3424     }
3425 
3426     @Test
3427     @RequiresFlagsEnabled(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
testRegisterForCapabilitiesChanged()3428     public void testRegisterForCapabilitiesChanged() {
3429         if (!shouldTestSatelliteWithMockService()) return;
3430 
3431         logd("testRegisterForCapabilitiesChanged: start");
3432         grantSatellitePermission();
3433 
3434         android.telephony.satellite.stub.SatelliteCapabilities capabilities =
3435                 new android.telephony.satellite.stub.SatelliteCapabilities();
3436         int[] supportedRadioTechnologies =
3437                 new int[]{android.telephony.satellite.stub.NTRadioTechnology.NB_IOT_NTN};
3438         capabilities.supportedRadioTechnologies = supportedRadioTechnologies;
3439         int[] antennaPositionKeys = new int[]{
3440                 SatelliteManager.DISPLAY_MODE_OPENED, SatelliteManager.DISPLAY_MODE_CLOSED};
3441         AntennaPosition[] antennaPositionValues = new AntennaPosition[] {
3442                 new AntennaPosition(new AntennaDirection(1, 1, 1),
3443                         SatelliteManager.DEVICE_HOLD_POSITION_PORTRAIT),
3444                 new AntennaPosition(new AntennaDirection(2, 2, 2),
3445                         SatelliteManager.DEVICE_HOLD_POSITION_LANDSCAPE_LEFT)
3446         };
3447 
3448         capabilities.isPointingRequired = POINTING_TO_SATELLITE_REQUIRED;
3449         capabilities.maxBytesPerOutgoingDatagram = MAX_BYTES_PER_DATAGRAM;
3450         capabilities.antennaPositionKeys = antennaPositionKeys;
3451         capabilities.antennaPositionValues = antennaPositionValues;
3452         SatelliteCapabilities frameworkCapabilities =
3453                 SatelliteServiceUtils.fromSatelliteCapabilities(capabilities);
3454         SatelliteCapabilitiesCallbackTest satelliteCapabilitiesCallbackTest =
3455                 new SatelliteCapabilitiesCallbackTest();
3456 
3457         /* register callback for satellite capabilities changed event */
3458         @SatelliteManager.SatelliteResult int registerError =
3459                 sSatelliteManager.registerForCapabilitiesChanged(
3460                         getContext().getMainExecutor(), satelliteCapabilitiesCallbackTest);
3461         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerError);
3462 
3463         /* Verify whether capability changed event has received */
3464         sendOnSatelliteCapabilitiesChanged(capabilities);
3465         assertTrue(satelliteCapabilitiesCallbackTest.waitUntilResult(1));
3466         assertTrue(frameworkCapabilities
3467                 .equals(satelliteCapabilitiesCallbackTest.mSatelliteCapabilities));
3468 
3469         /* Verify whether notified and requested capabilities are equal */
3470         Pair<SatelliteCapabilities, Integer> pairResult = requestSatelliteCapabilities();
3471         assertTrue(frameworkCapabilities.equals(pairResult.first));
3472         assertNull(pairResult.second);
3473 
3474         /* datagram size has changed */
3475         capabilities.maxBytesPerOutgoingDatagram = MAX_BYTES_PER_DATAGRAM + 1;
3476         frameworkCapabilities = SatelliteServiceUtils.fromSatelliteCapabilities(capabilities);
3477 
3478         /* Verify changed capabilities are reflected */
3479         sendOnSatelliteCapabilitiesChanged(capabilities);
3480         assertTrue(satelliteCapabilitiesCallbackTest.waitUntilResult(1));
3481         assertTrue(frameworkCapabilities
3482                 .equals(satelliteCapabilitiesCallbackTest.mSatelliteCapabilities));
3483 
3484         pairResult = requestSatelliteCapabilities();
3485         assertTrue(frameworkCapabilities.equals(pairResult.first));
3486         assertNull(pairResult.second);
3487 
3488         /* Initialize Radio technology */
3489         supportedRadioTechnologies =
3490                 new int[]{android.telephony.satellite.stub.NTRadioTechnology.PROPRIETARY};
3491         capabilities.supportedRadioTechnologies = supportedRadioTechnologies;
3492         sendOnSatelliteCapabilitiesChanged(capabilities);
3493         /* unregister non-terrestrial network signal strength changed event callback */
3494         sSatelliteManager.unregisterForCapabilitiesChanged(
3495                 satelliteCapabilitiesCallbackTest);
3496 
3497         revokeSatellitePermission();
3498     }
3499 
3500     @Test
3501     @RequiresFlagsEnabled(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
testSendSatelliteDatagram_DemoMode_WithDeviceConfig()3502     public void testSendSatelliteDatagram_DemoMode_WithDeviceConfig() {
3503         if (!shouldTestSatelliteWithMockService()) return;
3504 
3505         logd("testSendSatelliteDatagram_DemoMode_WithDeviceConfig");
3506         grantSatellitePermission();
3507         assertTrue(isSatelliteProvisioned());
3508 
3509         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
3510         sSatelliteManager.registerForModemStateChanged(
3511                 getContext().getMainExecutor(), stateCallback);
3512         assertTrue(stateCallback.waitUntilResult(1));
3513 
3514         // Enable satellite with demo mode on
3515         if (isSatelliteEnabled()) {
3516             requestSatelliteEnabled(false);
3517             assertTrue(stateCallback.waitUntilModemOff());
3518             stateCallback.clearModemStates();
3519         }
3520         requestSatelliteEnabledForDemoMode(true);
3521         assertTrue(stateCallback.waitUntilResult(2));
3522         assertTrue(isSatelliteEnabled());
3523         assertTrue(getIsEmergency());
3524         assertTrue(sMockSatelliteServiceManager.setShouldSendDatagramToModemInDemoMode(false));
3525 
3526         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
3527         SatelliteTransmissionUpdateCallbackTest callback =
3528                 new SatelliteTransmissionUpdateCallbackTest();
3529         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
3530                 resultListener::offer, callback);
3531         Integer errorCode;
3532         try {
3533             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
3534         } catch (InterruptedException ex) {
3535             fail("testSendSatelliteDatagram_DemoMode_WithDeviceConfig: Got InterruptedException "
3536                     + "in waiting for the startSatelliteTransmissionUpdates result code");
3537             return;
3538         }
3539         assertNotNull(errorCode);
3540         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
3541 
3542         // Send satellite datagram
3543         String mText = "This is a test datagram message from user";
3544         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
3545         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(false,
3546                 DatagramController.TIMEOUT_TYPE_DATAGRAM_DELAY_IN_DEMO_MODE,
3547                 TEST_DATAGRAM_DELAY_IN_DEMO_MODE_TIMEOUT_MILLIS));
3548         callback.clearSendDatagramStateChanges();
3549         sMockSatelliteServiceManager.setErrorCode(SatelliteManager.SATELLITE_RESULT_SUCCESS);
3550         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
3551                 datagram, true, getContext().getMainExecutor(),
3552                 resultListener::offer);
3553         sSatelliteManager.setDeviceAlignedWithSatellite(true);
3554         // Satellite datagram does not send to satellite modem.
3555         sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(0);
3556         try {
3557             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
3558         } catch (InterruptedException ex) {
3559             fail("testSendSatelliteDatagram_DemoMode_WithDeviceConfig: Got InterruptedException "
3560                     + "in waiting for the sendDatagram result code");
3561             return;
3562         }
3563         assertNotNull(errorCode);
3564         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
3565 
3566         /*
3567          * Send datagram transfer state should have the following transitions:
3568          * 1) IDLE to SENDING
3569          * 2) SENDING to SEND_SUCCESS
3570          * 3) SEND_SUCCESS to IDLE
3571          */
3572         int expectedNumOfEvents = 3;
3573         assertTrue(callback.waitUntilOnSendDatagramStateChanged(expectedNumOfEvents));
3574         assertThat(callback.getNumOfSendDatagramStateChanges()).isEqualTo(expectedNumOfEvents);
3575         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
3576                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3577                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
3578                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3579         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
3580                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3581                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
3582                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3583         assertThat(callback.getSendDatagramStateChange(2)).isEqualTo(
3584                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3585                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
3586                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3587 
3588         callback.clearSendDatagramStateChanges();
3589         sSatelliteManager.stopTransmissionUpdates(callback, getContext().getMainExecutor(),
3590                 resultListener::offer);
3591         sSatelliteManager.unregisterForModemStateChanged(stateCallback);
3592         assertTrue(sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(true,
3593                 DatagramController.TIMEOUT_TYPE_DATAGRAM_DELAY_IN_DEMO_MODE, 0));
3594         revokeSatellitePermission();
3595     }
3596 
3597     @Test
3598     @RequiresFlagsEnabled(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
testSatelliteAccessControl()3599     public void testSatelliteAccessControl() {
3600         if (!shouldTestSatelliteWithMockService()) return;
3601 
3602         grantSatellitePermission();
3603         assertTrue(sMockSatelliteServiceManager
3604                 .setIsSatelliteCommunicationAllowedForCurrentLocationCache(
3605                         "cache_clear_and_not_allowed"));
3606         SatelliteCommunicationAllowedStateCallbackTest allowStatecallback =
3607                 new SatelliteCommunicationAllowedStateCallbackTest();
3608         long registerResultAllowState = sSatelliteManager
3609                 .registerForCommunicationAllowedStateChanged(
3610                         getContext().getMainExecutor(), allowStatecallback);
3611         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResultAllowState);
3612 
3613         /*
3614         // Test access controller using cached country codes
3615         assertTrue(sMockSatelliteServiceManager.setSatelliteAccessControlOverlayConfigs(
3616                 false, true, null, 0, SATELLITE_COUNTRY_CODES));
3617 
3618         verifyIsSatelliteAllowed(true);
3619 
3620         // Allowed case
3621         assertTrue(sMockSatelliteServiceManager.setCountryCodes(false, null, null, "US",
3622                 SystemClock.elapsedRealtimeNanos()));
3623         verifyIsSatelliteAllowed(true);
3624         assertTrue(allowStatecallback.waitUntilResult(0));
3625 
3626         // Disallowed case
3627         assertTrue(sMockSatelliteServiceManager.setCountryCodes(false, null, null, "IN",
3628                 SystemClock.elapsedRealtimeNanos()));
3629         verifyIsSatelliteAllowed(false);
3630         assertTrue(allowStatecallback.waitUntilResult(1));
3631         assertFalse(allowStatecallback.isAllowed);
3632         */
3633 
3634         // Test access controller using on-device data
3635         assertTrue(sMockSatelliteServiceManager.setCountryCodes(false, null, null, null, 0));
3636         assertTrue(sMockSatelliteServiceManager.setSatelliteAccessControlOverlayConfigs(
3637                 false, true, SATELLITE_S2_FILE, TimeUnit.MINUTES.toNanos(10), "US"));
3638         registerTestLocationProvider();
3639 
3640         // Set current location to Google San Diego office
3641         setTestProviderLocation(32.909808231041644, -117.18185788819781);
3642         verifyIsSatelliteAllowed(true);
3643         assertTrue(allowStatecallback.waitUntilResult(1));
3644         assertTrue(allowStatecallback.isAllowed);
3645 
3646         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
3647         long registerResult = sSatelliteManager.registerForModemStateChanged(
3648                 getContext().getMainExecutor(), callback);
3649         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
3650         assertTrue(callback.waitUntilResult(1));
3651         if (!isSatelliteEnabled()) {
3652             requestSatelliteEnabled(true);
3653             assertTrue(callback.waitUntilResult(1));
3654             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.modemState);
3655             assertTrue(isSatelliteEnabled());
3656         }
3657 
3658         assertTrue(sMockSatelliteServiceManager
3659                 .setIsSatelliteCommunicationAllowedForCurrentLocationCache("clear_cache_only"));
3660 
3661         // Set current location to Google Bangalore office
3662         setTestProviderLocation(12.994021769576554, 12.994021769576554);
3663         verifyIsSatelliteAllowed(false);
3664         assertTrue(allowStatecallback.waitUntilResult(1));
3665         assertFalse(allowStatecallback.isAllowed);
3666 
3667         // Even though satellite is not allowed at the current location, disabling satellite should
3668         // succeed
3669         requestSatelliteEnabled(false);
3670         assertTrue(callback.waitUntilModemOff());
3671         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
3672         assertFalse(isSatelliteEnabled());
3673 
3674         // Restore satellite access allowed
3675         setUpSatelliteAccessAllowed();
3676         revokeSatellitePermission();
3677         unregisterTestLocationProvider();
3678     }
3679 
3680     @Test
3681     @FlaggedApi(Flags.FLAG_CARRIER_ENABLED_SATELLITE_FLAG)
testGetSatellitePlmnsForCarrier()3682     public void testGetSatellitePlmnsForCarrier() {
3683         if (!shouldTestSatelliteWithMockService() || !Flags.carrierEnabledSatelliteFlag()) return;
3684 
3685         logd("testGetAggregateSatellitePlmnListForCarrier");
3686         grantSatellitePermission();
3687         beforeSatelliteForCarrierTest();
3688         @SatelliteManager.SatelliteResult int expectedSuccess =
3689                 SatelliteManager.SATELLITE_RESULT_SUCCESS;
3690 
3691         /* Test when satellite is supported in the carrier config */
3692         setSatelliteError(expectedSuccess);
3693         PersistableBundle bundle = new PersistableBundle();
3694         bundle.putBoolean(
3695                 CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
3696         PersistableBundle plmnBundle = new PersistableBundle();
3697         int[] intArray1 = {3, 5};
3698         int[] intArray2 = {3};
3699         plmnBundle.putIntArray("123411", intArray1);
3700         plmnBundle.putIntArray("123412", intArray2);
3701         bundle.putPersistableBundle(
3702                 CarrierConfigManager.KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
3703                 plmnBundle);
3704         overrideCarrierConfig(sTestSubIDForCarrierSatellite, bundle);
3705 
3706         ArrayList<String> expectedCarrierPlmnList = new ArrayList<>();
3707         expectedCarrierPlmnList.add("123411");
3708         expectedCarrierPlmnList.add("123412");
3709         assertTrue(sMockSatelliteServiceManager.waitForEventOnSetSatellitePlmn(1));
3710         List<String> carrierPlmnList = sMockSatelliteServiceManager.getCarrierPlmnList();
3711         assertNotNull(carrierPlmnList);
3712         assertEquals(expectedCarrierPlmnList, carrierPlmnList);
3713 
3714         /* Aggregated satellite plmn should be same with allSatellitePlmnList */
3715         List<String> aggregatedPlmnList = sSatelliteManager.getSatellitePlmnsForCarrier(
3716                 sTestSubIDForCarrierSatellite);
3717         List<String> satellitePlmnListFromOverlayConfig =
3718                 sMockSatelliteServiceManager.getPlmnListFromOverlayConfig();
3719         List<String> expectedAllSatellitePlmnList = SatelliteServiceUtils.mergeStrLists(
3720                 carrierPlmnList, satellitePlmnListFromOverlayConfig);
3721         List<String> allSatellitePlmnList = sMockSatelliteServiceManager.getAllSatellitePlmnList();
3722         assertNotNull(allSatellitePlmnList);
3723         assertEquals(expectedAllSatellitePlmnList, allSatellitePlmnList);
3724         assertEquals(expectedAllSatellitePlmnList, aggregatedPlmnList);
3725 
3726         afterSatelliteForCarrierTest();
3727         revokeSatellitePermission();
3728     }
3729 
3730     @Test
testSendSatelliteDatagrams_timeout()3731     public void testSendSatelliteDatagrams_timeout() {
3732         if (!shouldTestSatelliteWithMockService()) return;
3733 
3734         logd("testSendSatelliteDatagrams_timeout");
3735         grantSatellitePermission();
3736         assertTrue(isSatelliteProvisioned());
3737 
3738         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
3739         SatelliteTransmissionUpdateCallbackTest callback =
3740                 new SatelliteTransmissionUpdateCallbackTest();
3741         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
3742                 resultListener::offer, callback);
3743         Integer errorCode;
3744         try {
3745             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
3746         } catch (InterruptedException ex) {
3747             fail("testSendSatelliteDatagrams_timeout: Got InterruptedException in waiting"
3748                     + " for the sendDatagram result code");
3749             return;
3750         }
3751         assertNotNull(errorCode);
3752         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
3753 
3754         String mText = "This is a test datagram message from user";
3755         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
3756         callback.clearSendDatagramStateChanges();
3757         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
3758 
3759         // Wait to process datagrams so that the send request will time out.
3760         sMockSatelliteServiceManager.setWaitToSend(true);
3761         // Override the sending timeout duration to 1 second
3762         sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(false,
3763                 DatagramController.TIMEOUT_TYPE_WAIT_FOR_DATAGRAM_SENDING_RESPONSE, 1000);
3764 
3765         LinkedBlockingQueue<Integer> resultListener1 = new LinkedBlockingQueue<>(1);
3766         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
3767                 datagram, true, getContext().getMainExecutor(),
3768                 resultListener1::offer);
3769         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
3770 
3771         assertTrue(callback.waitUntilOnSendDatagramStateChanged(3));
3772         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
3773                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3774                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
3775                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3776         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
3777                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3778                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_FAILED,
3779                         1, SatelliteManager.SATELLITE_RESULT_MODEM_TIMEOUT));
3780         assertThat(callback.getSendDatagramStateChange(2)).isEqualTo(
3781                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
3782                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
3783                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
3784         try {
3785             errorCode = resultListener1.poll(TIMEOUT, TimeUnit.MILLISECONDS);
3786         } catch (InterruptedException ex) {
3787             fail("testSendSatelliteDatagrams_timeout: Got InterruptedException in waiting"
3788                     + " for the sendDatagram result code");
3789             return;
3790         }
3791         assertNotNull(errorCode);
3792         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_MODEM_TIMEOUT);
3793 
3794         // Respond to the first send request
3795         callback.clearSendDatagramStateChanges();
3796         assertTrue(sMockSatelliteServiceManager.sendSavedDatagram());
3797 
3798         // Telephony should ignore the response
3799         assertFalse(callback.waitUntilOnSendDatagramStateChanged(1));
3800 
3801         // Restore the timeout duration
3802         sMockSatelliteServiceManager.setDatagramControllerTimeoutDuration(true,
3803                 DatagramController.TIMEOUT_TYPE_WAIT_FOR_DATAGRAM_SENDING_RESPONSE, 0);
3804     }
3805     @Test
testRequestSatelliteEnabled_timeout()3806     public void testRequestSatelliteEnabled_timeout() {
3807         if (!shouldTestSatelliteWithMockService()) return;
3808 
3809         grantSatellitePermission();
3810         assertTrue(isSatelliteProvisioned());
3811 
3812         logd("testRequestSatelliteEnabled_timeout: starting...");
3813         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
3814         long registerResult = sSatelliteManager.registerForModemStateChanged(
3815                 getContext().getMainExecutor(), callback);
3816         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
3817         assertTrue(callback.waitUntilResult(1));
3818         if (isSatelliteEnabled()) {
3819             logd("testRequestSatelliteEnabled_timeout: disabling satellite...");
3820             requestSatelliteEnabled(false);
3821             assertTrue(callback.waitUntilModemOff());
3822             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
3823             assertFalse(isSatelliteEnabled());
3824             callback.clearModemStates();
3825         }
3826 
3827         sMockSatelliteServiceManager.setShouldRespondTelephony(false);
3828         assertTrue(sMockSatelliteServiceManager.setSatelliteControllerTimeoutDuration(false,
3829                 TIMEOUT_TYPE_WAIT_FOR_SATELLITE_ENABLING_RESPONSE, 500));
3830 
3831         // Time out to enable satellite
3832         logd("testRequestSatelliteEnabled_timeout: enabling satellite...");
3833         int result = requestSatelliteEnabledWithResult(true, TIMEOUT);
3834         assertEquals(SatelliteManager.SATELLITE_RESULT_MODEM_TIMEOUT, result);
3835         assertTrue(callback.waitUntilResult(2));
3836         assertEquals(2, callback.getTotalCountOfModemStates());
3837         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
3838                 callback.getModemState(0));
3839         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.getModemState(1));
3840         assertFalse(isSatelliteEnabled());
3841         assertTrue(sMockSatelliteServiceManager.waitForEventOnRequestSatelliteEnabled(1));
3842 
3843         // Respond to the above enable request. Telephony should ignore the event.
3844         logd("testRequestSatelliteEnabled_timeout: Responding the enabling request...");
3845         callback.clearModemStates();
3846         assertTrue(sMockSatelliteServiceManager.respondToRequestSatelliteEnabled(true));
3847         assertFalse(callback.waitUntilResult(1));
3848         assertFalse(isSatelliteEnabled());
3849 
3850         // Restore the original states
3851         sMockSatelliteServiceManager.setShouldRespondTelephony(true);
3852         assertTrue(sMockSatelliteServiceManager.setSatelliteControllerTimeoutDuration(true,
3853                 TIMEOUT_TYPE_WAIT_FOR_SATELLITE_ENABLING_RESPONSE, 0));
3854 
3855         // Successfully enable satellite
3856         logd("testRequestSatelliteEnabled_timeout: enabling satellite...");
3857         callback.clearModemStates();
3858         requestSatelliteEnabled(true);
3859         assertTrue(callback.waitUntilResult(2));
3860         assertEquals(2, callback.getTotalCountOfModemStates());
3861         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_ENABLING_SATELLITE,
3862                 callback.getModemState(0));
3863         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE, callback.getModemState(1));
3864 
3865         sMockSatelliteServiceManager.setShouldRespondTelephony(false);
3866         assertTrue(sMockSatelliteServiceManager.setSatelliteControllerTimeoutDuration(false,
3867                 TIMEOUT_TYPE_WAIT_FOR_SATELLITE_ENABLING_RESPONSE, 500));
3868 
3869         // Time out to disable satellite. Telephony should respond SATELLITE_RESULT_MODEM_TIMEOUT to
3870         // clients and move to SATELLITE_MODEM_STATE_OFF
3871         logd("testRequestSatelliteEnabled_timeout: disabling satellite...");
3872         callback.clearModemStates();
3873         result = requestSatelliteEnabledWithResult(false, TIMEOUT);
3874         assertEquals(SatelliteManager.SATELLITE_RESULT_MODEM_TIMEOUT, result);
3875         assertTrue(callback.waitUntilModemOff());
3876         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_OFF, callback.modemState);
3877         assertFalse(isSatelliteEnabled());
3878         assertTrue(sMockSatelliteServiceManager.waitForEventOnRequestSatelliteEnabled(1));
3879 
3880         // Respond to the above disable request. Telephony should ignore the event.
3881         logd("testRequestSatelliteEnabled_timeout: Responding the disabling request...");
3882         callback.clearModemStates();
3883         assertTrue(sMockSatelliteServiceManager.respondToRequestSatelliteEnabled(false));
3884         assertFalse(callback.waitUntilResult(1));
3885         assertFalse(isSatelliteEnabled());
3886 
3887         // Restore the original states
3888         sMockSatelliteServiceManager.setShouldRespondTelephony(true);
3889         assertTrue(sMockSatelliteServiceManager.setSatelliteControllerTimeoutDuration(true,
3890                 TIMEOUT_TYPE_WAIT_FOR_SATELLITE_ENABLING_RESPONSE, 0));
3891     }
3892 
3893     @Test
3894     @RequiresFlagsEnabled(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
testRegisterForSupportedStateChanged()3895     public void testRegisterForSupportedStateChanged() {
3896         if (!shouldTestSatelliteWithMockService()) return;
3897 
3898         logd("testRegisterForSupportedStateChanged: start");
3899         grantSatellitePermission();
3900 
3901         /* Backup satellite supported state */
3902         final Pair<Boolean, Integer> originalSupportState = requestIsSatelliteSupported();
3903 
3904         SatelliteSupportedStateCallbackTest satelliteSupportedStateCallbackTest =
3905                 new SatelliteSupportedStateCallbackTest();
3906 
3907         /* Register callback for satellite supported state changed event */
3908         @SatelliteManager.SatelliteResult int registerError =
3909                 sSatelliteManager.registerForSupportedStateChanged(
3910                         getContext().getMainExecutor(), satelliteSupportedStateCallbackTest);
3911         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerError);
3912 
3913         /* Verify redundant report is ignored */
3914         sendOnSatelliteSupportedStateChanged(true);
3915         assertFalse(satelliteSupportedStateCallbackTest.waitUntilResult(1));
3916 
3917         /* Satellite is unsupported */
3918         sendOnSatelliteSupportedStateChanged(false);
3919         assertTrue(satelliteSupportedStateCallbackTest.waitUntilResult(1));
3920         assertFalse(satelliteSupportedStateCallbackTest.isSupported);
3921 
3922         /* Verify satellite is disabled */
3923         Pair<Boolean, Integer> pairResult = requestIsSatelliteSupported();
3924         assertFalse(pairResult.first);
3925         assertNull(pairResult.second);
3926 
3927         /* Verify redundant report is ignored */
3928         sendOnSatelliteSupportedStateChanged(false);
3929         assertFalse(satelliteSupportedStateCallbackTest.waitUntilResult(1));
3930 
3931         /* Verify whether satellite support changed event has received */
3932         sendOnSatelliteSupportedStateChanged(true);
3933         assertTrue(satelliteSupportedStateCallbackTest.waitUntilResult(1));
3934         assertTrue(satelliteSupportedStateCallbackTest.isSupported);
3935 
3936         /* Verify whether notified and requested capabilities are equal */
3937         pairResult = requestIsSatelliteSupported();
3938         assertTrue(pairResult.first);
3939         assertNull(pairResult.second);
3940 
3941         /* Verify redundant report is ignored */
3942         sendOnSatelliteSupportedStateChanged(true);
3943         assertFalse(satelliteSupportedStateCallbackTest.waitUntilResult(1));
3944 
3945         /* Restore initial satellite support state */
3946         sendOnSatelliteSupportedStateChanged(originalSupportState.first);
3947         satelliteSupportedStateCallbackTest.clearSupportedStates();
3948 
3949         sSatelliteManager.unregisterForSupportedStateChanged(satelliteSupportedStateCallbackTest);
3950         revokeSatellitePermission();
3951     }
3952 
3953     @Test
3954     @RequiresFlagsEnabled(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
testDemoSimulator()3955     public void testDemoSimulator() {
3956         if (!shouldTestSatelliteWithMockService()) return;
3957 
3958         logd("testDemoSimulator: start");
3959         updateSupportedRadioTechnologies(new int[]{NTRadioTechnology.NB_IOT_NTN}, true);
3960 
3961         grantSatellitePermission();
3962         assertTrue(isSatelliteProvisioned());
3963         assertTrue(isSatelliteEnabled());
3964 
3965         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
3966         sSatelliteManager.registerForModemStateChanged(
3967                 getContext().getMainExecutor(), stateCallback);
3968         assertTrue(stateCallback.waitUntilResult(1));
3969 
3970         NtnSignalStrengthCallbackTest ntnSignalStrengthCallback =
3971                 new NtnSignalStrengthCallbackTest();
3972         /* register callback for non-terrestrial network signal strength changed event */
3973         sSatelliteManager.registerForNtnSignalStrengthChanged(getContext().getMainExecutor(),
3974                 ntnSignalStrengthCallback);
3975 
3976         assertTrue(sMockSatelliteServiceManager.setSatelliteControllerTimeoutDuration(false,
3977                 TIMEOUT_TYPE_DEMO_POINTING_ALIGNED_DURATION_MILLIS, 5));
3978         assertTrue(sMockSatelliteServiceManager.setSatelliteControllerTimeoutDuration(false,
3979                 TIMEOUT_TYPE_DEMO_POINTING_NOT_ALIGNED_DURATION_MILLIS, 10));
3980 
3981         try {
3982             logd("testDemoSimulator: Disable satellite");
3983             requestSatelliteEnabled(false);
3984             assertTrue(stateCallback.waitUntilModemOff());
3985             assertFalse(isSatelliteEnabled());
3986             stateCallback.clearModemStates();
3987 
3988             logd("testDemoSimulator: Enable satellite for demo mode");
3989             stateCallback.clearModemStates();
3990             requestSatelliteEnabledForDemoMode(true);
3991             assertTrue(stateCallback.waitUntilResult(2));
3992             assertTrue(isSatelliteEnabled());
3993             assertTrue(ntnSignalStrengthCallback.waitUntilResult(1));
3994             assertEquals(NtnSignalStrength.NTN_SIGNAL_STRENGTH_NONE,
3995                     ntnSignalStrengthCallback.mNtnSignalStrength.getLevel());
3996 
3997             logd("testDemoSimulator: Set device aligned with satellite");
3998             stateCallback.clearModemStates();
3999             sSatelliteManager.setDeviceAlignedWithSatellite(true);
4000             assertTrue(stateCallback.waitUntilResult(1));
4001             assertTrue(ntnSignalStrengthCallback.waitUntilResult(1));
4002             assertEquals(NtnSignalStrength.NTN_SIGNAL_STRENGTH_MODERATE,
4003                     ntnSignalStrengthCallback.mNtnSignalStrength.getLevel());
4004 
4005             logd("testDemoSimulator: Set device not aligned with satellite");
4006             stateCallback.clearModemStates();
4007             sSatelliteManager.setDeviceAlignedWithSatellite(false);
4008             assertTrue(stateCallback.waitUntilResult(1));
4009             assertTrue(ntnSignalStrengthCallback.waitUntilResult(1));
4010             assertEquals(NtnSignalStrength.NTN_SIGNAL_STRENGTH_NONE,
4011                     ntnSignalStrengthCallback.mNtnSignalStrength.getLevel());
4012 
4013             logd("testDemoSimulator: Disable satellite for demo mode");
4014             stateCallback.clearModemStates();
4015             requestSatelliteEnabledForDemoMode(false);
4016             assertTrue(stateCallback.waitUntilResult(2));
4017             assertFalse(isSatelliteEnabled());
4018         } finally {
4019             assertTrue(sMockSatelliteServiceManager.setSatelliteControllerTimeoutDuration(
4020                     true, TIMEOUT_TYPE_DEMO_POINTING_ALIGNED_DURATION_MILLIS, 0));
4021             assertTrue(sMockSatelliteServiceManager.setSatelliteControllerTimeoutDuration(
4022                     true, TIMEOUT_TYPE_DEMO_POINTING_NOT_ALIGNED_DURATION_MILLIS, 0));
4023 
4024             sSatelliteManager.unregisterForNtnSignalStrengthChanged(ntnSignalStrengthCallback);
4025             sSatelliteManager.unregisterForModemStateChanged(stateCallback);
4026             updateSupportedRadioTechnologies(new int[]{NTRadioTechnology.PROPRIETARY}, false);
4027             revokeSatellitePermission();
4028         }
4029     }
4030 
4031     @Test
4032     @RequiresFlagsEnabled(Flags.FLAG_OEM_ENABLED_SATELLITE_FLAG)
testRequestSessionStats()4033     public void testRequestSessionStats() {
4034         if (!shouldTestSatelliteWithMockService()) return;
4035 
4036         logd("testRequestSessionStats: start");
4037         grantSatellitePermission();
4038         assertTrue(isSatelliteProvisioned());
4039         assertTrue(isSatelliteEnabled());
4040 
4041         SatelliteModemStateCallbackTest stateCallback = new SatelliteModemStateCallbackTest();
4042         sSatelliteManager.registerForModemStateChanged(
4043                 getContext().getMainExecutor(), stateCallback);
4044         assertTrue(stateCallback.waitUntilResult(1));
4045 
4046         try {
4047             SatelliteSessionStats sessionStats = new SatelliteSessionStats.Builder()
4048                     .setCountOfSuccessfulUserMessages(0)
4049                     .setCountOfUnsuccessfulUserMessages(0)
4050                     .setCountOfTimedOutUserMessagesWaitingForConnection(0)
4051                     .setCountOfTimedOutUserMessagesWaitingForAck(0)
4052                     .setCountOfUserMessagesInQueueToBeSent(0)
4053                     .build();
4054             Pair<SatelliteSessionStats, Integer> result = requestSessionStats();
4055             assertEquals(sessionStats, result.first);
4056 
4057             sessionStats = new SatelliteSessionStats.Builder()
4058                     .setCountOfSuccessfulUserMessages(5)
4059                     .setCountOfUnsuccessfulUserMessages(2)
4060                     .setCountOfTimedOutUserMessagesWaitingForConnection(0)
4061                     .setCountOfTimedOutUserMessagesWaitingForAck(0)
4062                     .setCountOfUserMessagesInQueueToBeSent(4)
4063                     .build();
4064 
4065             for (int i = 0; i < 5; i++) {
4066                 sendSatelliteDatagramSuccess(true, true);
4067             }
4068 
4069             LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4070             String mText = "This is a test datagram message from user";
4071             SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
4072 
4073             for (int i = 0; i < 2; i++) {
4074                 stateCallback.clearModemStates();
4075                 sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_ERROR);
4076                 sSatelliteManager.sendDatagram(
4077                         SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE, datagram, true,
4078                         getContext().getMainExecutor(), resultListener::offer);
4079 
4080                 Integer errorCode;
4081                 try {
4082                     errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4083                 } catch (InterruptedException ex) {
4084                     fail("testSendSatelliteDatagram_failure: Got InterruptedException in waiting"
4085                             + " for the sendSatelliteDatagram result code");
4086                     return;
4087                 }
4088                 assertNotNull(errorCode);
4089                 assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_ERROR);
4090             }
4091 
4092             // Wait to process datagrams so that datagrams are added to pending list.
4093             sMockSatelliteServiceManager.setWaitToSend(true);
4094             for (int i = 0; i < 4; i++) {
4095                 // Send 4 user messages
4096                 sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
4097                         datagram, true, getContext().getMainExecutor(),
4098                         resultListener::offer);
4099             }
4100 
4101             // Send 1 keep alive message
4102             // This should be ignored and not be included in pending datagrams count
4103             sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_KEEP_ALIVE,
4104                     datagram, true, getContext().getMainExecutor(),
4105                     resultListener::offer);
4106 
4107             result = requestSessionStats();
4108             assertEquals(sessionStats, result.first);
4109 
4110             sMockSatelliteServiceManager.setWaitToSend(false);
4111         } finally {
4112             revokeSatellitePermission();
4113         }
4114     }
4115 
4116     /*
4117      * Before calling this function, caller need to make sure the modem is in LISTENING or IDLE
4118      * state.
4119      */
sendSatelliteDatagramWithSuccessfulResult( SatelliteModemStateCallbackTest callback, boolean verifyListenToIdleTransition)4120     private void sendSatelliteDatagramWithSuccessfulResult(
4121             SatelliteModemStateCallbackTest callback, boolean verifyListenToIdleTransition) {
4122         if (callback.modemState != SatelliteManager.SATELLITE_MODEM_STATE_LISTENING
4123                 && callback.modemState != SatelliteManager.SATELLITE_MODEM_STATE_IDLE) {
4124             fail("sendSatelliteDatagramWithSuccessfulResult: wrong modem state="
4125                     + callback.modemState);
4126             return;
4127         }
4128 
4129         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4130         String mText = "This is a test datagram message from user";
4131         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
4132 
4133         sMockSatelliteServiceManager.clearListeningEnabledList();
4134         callback.clearModemStates();
4135         sSatelliteManager.sendDatagram(
4136                 SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE, datagram, true,
4137                 getContext().getMainExecutor(), resultListener::offer);
4138 
4139         Integer errorCode;
4140         try {
4141             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4142         } catch (InterruptedException ex) {
4143             fail("testSatelliteModemStateChanged: Got InterruptedException in waiting"
4144                     + " for the sendDatagram result code");
4145             return;
4146         }
4147         assertNotNull(errorCode);
4148         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, (long) errorCode);
4149 
4150         /*
4151          * Modem state should have the following transitions:
4152          * 1) IDLE to TRANSFERRING.
4153          * 2) TRANSFERRING to LISTENING.
4154          * 3) LISTENING to IDLE.
4155          *
4156          * When verifyListenToIdleTransition is true, we expect the above 3 state transitions.
4157          * Otherwise, we expect only the first 2 transitions since satellite is still in LISTENING
4158          * state (timeout duration is long when verifyListenToIdleTransition is false).
4159          */
4160         int expectedNumberOfEvents = verifyListenToIdleTransition ? 3 : 2;
4161         assertTrue(callback.waitUntilResult(expectedNumberOfEvents));
4162         assertEquals(expectedNumberOfEvents, callback.getTotalCountOfModemStates());
4163         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DATAGRAM_TRANSFERRING,
4164                 callback.getModemState(0));
4165         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_LISTENING,
4166                 callback.getModemState(1));
4167 
4168         /*
4169          * On entering LISTENING state, we expect one event of EventOnSatelliteListeningEnabled with
4170          * value true. On exiting LISTENING state, we expect one event of
4171          * EventOnSatelliteListeningEnabled with value false.
4172          *
4173          * When verifyListenToIdleTransition is true, we expect satellite entering and then exiting
4174          * LISTENING state. Otherwise, we expect satellite entering and staying at LISTENING state.
4175          */
4176         expectedNumberOfEvents = verifyListenToIdleTransition ? 2 : 1;
4177         assertTrue(sMockSatelliteServiceManager.waitForEventOnSatelliteListeningEnabled(
4178                 expectedNumberOfEvents));
4179         assertEquals(expectedNumberOfEvents,
4180                 sMockSatelliteServiceManager.getTotalCountOfListeningEnabledList());
4181         assertTrue(sMockSatelliteServiceManager.getListeningEnabled(0));
4182 
4183         if (verifyListenToIdleTransition) {
4184             assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE,
4185                     callback.getModemState(2));
4186             assertFalse(sMockSatelliteServiceManager.getListeningEnabled(1));
4187         }
4188         sMockSatelliteServiceManager.clearListeningEnabledList();
4189     }
4190 
4191     /*
4192      * Before calling this function, caller need to make sure the modem is in LISTENING or IDLE
4193      * state.
4194      */
sendSatelliteDatagramWithFailedResult(SatelliteModemStateCallbackTest callback)4195     private void sendSatelliteDatagramWithFailedResult(SatelliteModemStateCallbackTest callback) {
4196         if (callback.modemState != SatelliteManager.SATELLITE_MODEM_STATE_LISTENING
4197                 && callback.modemState != SatelliteManager.SATELLITE_MODEM_STATE_IDLE) {
4198             fail("sendSatelliteDatagramWithFailedResult: wrong modem state=" + callback.modemState);
4199             return;
4200         }
4201         boolean isFirstStateListening =
4202                 (callback.modemState == SatelliteManager.SATELLITE_MODEM_STATE_LISTENING);
4203 
4204         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4205         String mText = "This is a test datagram message from user";
4206         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
4207 
4208         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_ERROR);
4209         sMockSatelliteServiceManager.clearListeningEnabledList();
4210         callback.clearModemStates();
4211         sSatelliteManager.sendDatagram(
4212                 SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE, datagram, true,
4213                 getContext().getMainExecutor(), resultListener::offer);
4214 
4215         Integer errorCode;
4216         try {
4217             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4218         } catch (InterruptedException ex) {
4219             fail("testSatelliteModemStateChanged: Got InterruptedException in waiting"
4220                     + " for the sendDatagram result code");
4221             return;
4222         }
4223         assertNotNull(errorCode);
4224         assertEquals(SatelliteManager.SATELLITE_RESULT_ERROR, (long) errorCode);
4225         assertTrue(callback.waitUntilResult(2));
4226         assertEquals(2, callback.getTotalCountOfModemStates());
4227         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DATAGRAM_TRANSFERRING,
4228                 callback.getModemState(0));
4229         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE,
4230                 callback.getModemState(1));
4231 
4232         if (isFirstStateListening) {
4233             assertTrue(sMockSatelliteServiceManager.waitForEventOnSatelliteListeningEnabled(1));
4234             assertEquals(1, sMockSatelliteServiceManager.getTotalCountOfListeningEnabledList());
4235             assertFalse(sMockSatelliteServiceManager.getListeningEnabled(0));
4236         }
4237         sMockSatelliteServiceManager.clearListeningEnabledList();
4238         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_SUCCESS);
4239     }
4240 
4241     /*
4242      * Before calling this function, caller need to make sure the modem is in LISTENING state.
4243      */
receiveSatelliteDatagramWithSuccessfulResult( SatelliteModemStateCallbackTest callback)4244     private void receiveSatelliteDatagramWithSuccessfulResult(
4245             SatelliteModemStateCallbackTest callback) {
4246         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_LISTENING, callback.modemState);
4247 
4248         // TODO (b/275086547): remove the below registerForIncomingDatagram command when the bug
4249         // is resolved.
4250         SatelliteDatagramCallbackTest satelliteDatagramCallback =
4251                 new SatelliteDatagramCallbackTest();
4252         sSatelliteManager.registerForIncomingDatagram(
4253                 getContext().getMainExecutor(), satelliteDatagramCallback);
4254 
4255         sMockSatelliteServiceManager.clearListeningEnabledList();
4256         callback.clearModemStates();
4257         sMockSatelliteServiceManager.sendOnPendingDatagrams();
4258         assertTrue(sMockSatelliteServiceManager.waitForEventOnPollPendingSatelliteDatagrams(1));
4259 
4260         assertTrue(callback.waitUntilResult(1));
4261         assertEquals(1, callback.getTotalCountOfModemStates());
4262         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DATAGRAM_TRANSFERRING,
4263                 callback.getModemState(0));
4264 
4265         assertTrue(sMockSatelliteServiceManager.waitForEventOnSatelliteListeningEnabled(1));
4266         assertEquals(1, sMockSatelliteServiceManager.getTotalCountOfListeningEnabledList());
4267         assertFalse(sMockSatelliteServiceManager.getListeningEnabled(0));
4268 
4269         String receivedText = "This is a test datagram message from satellite";
4270         android.telephony.satellite.stub.SatelliteDatagram receivedDatagram =
4271                 new android.telephony.satellite.stub.SatelliteDatagram();
4272         receivedDatagram.data = receivedText.getBytes();
4273 
4274         sMockSatelliteServiceManager.clearListeningEnabledList();
4275         callback.clearModemStates();
4276         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 0);
4277         assertTrue(callback.waitUntilResult(1));
4278         assertEquals(1, callback.getTotalCountOfModemStates());
4279         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_LISTENING,
4280                 callback.getModemState(0));
4281 
4282         assertTrue(sMockSatelliteServiceManager.waitForEventOnSatelliteListeningEnabled(1));
4283         assertEquals(1, sMockSatelliteServiceManager.getTotalCountOfListeningEnabledList());
4284         assertTrue(sMockSatelliteServiceManager.getListeningEnabled(0));
4285         sMockSatelliteServiceManager.clearListeningEnabledList();
4286 
4287         sSatelliteManager.unregisterForIncomingDatagram(satelliteDatagramCallback);
4288     }
4289 
4290     /*
4291      * Before calling this function, caller need to make sure the modem is in LISTENING state.
4292      */
receiveSatelliteDatagramWithFailedResult( SatelliteModemStateCallbackTest callback)4293     private void receiveSatelliteDatagramWithFailedResult(
4294             SatelliteModemStateCallbackTest callback) {
4295         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_LISTENING, callback.modemState);
4296 
4297         // TODO (b/275086547): remove the below registerForIncomingDatagram command when the bug
4298         // is resolved.
4299         SatelliteDatagramCallbackTest satelliteDatagramCallback =
4300                 new SatelliteDatagramCallbackTest();
4301         sSatelliteManager.registerForIncomingDatagram(
4302                 getContext().getMainExecutor(), satelliteDatagramCallback);
4303 
4304         sMockSatelliteServiceManager.clearListeningEnabledList();
4305         callback.clearModemStates();
4306         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_ERROR);
4307         sMockSatelliteServiceManager.sendOnPendingDatagrams();
4308         assertTrue(sMockSatelliteServiceManager.waitForEventOnPollPendingSatelliteDatagrams(1));
4309 
4310         assertTrue(callback.waitUntilResult(2));
4311         assertEquals(2, callback.getTotalCountOfModemStates());
4312         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_DATAGRAM_TRANSFERRING,
4313                 callback.getModemState(0));
4314         assertEquals(SatelliteManager.SATELLITE_MODEM_STATE_IDLE,
4315                 callback.getModemState(1));
4316 
4317         /*
4318          * On entering LISTENING state, we expect one event of EventOnSatelliteListeningEnabled with
4319          * value true. On exiting LISTENING state, we expect one event of
4320          * EventOnSatelliteListeningEnabled with value false.
4321          *
4322          * At the beginning of this function, satellite is in LISTENING state. It then transitions
4323          * to TRANSFERRING state. Thus, we expect one event of EventOnSatelliteListeningEnabled with
4324          * value false.
4325          */
4326         assertTrue(sMockSatelliteServiceManager.waitForEventOnSatelliteListeningEnabled(1));
4327         assertEquals(1, sMockSatelliteServiceManager.getTotalCountOfListeningEnabledList());
4328         assertFalse(sMockSatelliteServiceManager.getListeningEnabled(0));
4329 
4330         sMockSatelliteServiceManager.clearListeningEnabledList();
4331         sSatelliteManager.unregisterForIncomingDatagram(satelliteDatagramCallback);
4332         sMockSatelliteServiceManager.setErrorCode(SatelliteResult.SATELLITE_RESULT_SUCCESS);
4333     }
4334 
moveToSendingState()4335     private void moveToSendingState() {
4336         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4337         SatelliteTransmissionUpdateCallbackTest callback =
4338                 new SatelliteTransmissionUpdateCallbackTest();
4339         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
4340                 resultListener::offer, callback);
4341         Integer errorCode;
4342         try {
4343             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4344         } catch (InterruptedException ex) {
4345             fail("moveToSendingState: Got InterruptedException in waiting"
4346                     + " for the startSatelliteTransmissionUpdates result code");
4347             return;
4348         }
4349         assertNotNull(errorCode);
4350         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
4351 
4352         // Send satellite datagram
4353         String mText = "This is a test datagram message from user";
4354         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
4355         callback.clearSendDatagramStateChanges();
4356         sMockSatelliteServiceManager.setShouldRespondTelephony(false);
4357         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
4358         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
4359                 datagram, true, getContext().getMainExecutor(),
4360                 resultListener::offer);
4361 
4362         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
4363 
4364         // Send datagram transfer state should move from IDLE to SENDING.
4365         assertSingleSendDatagramStateChanged(callback,
4366                 SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
4367                 1, SatelliteManager.SATELLITE_RESULT_SUCCESS);
4368 
4369         sMockSatelliteServiceManager.setShouldRespondTelephony(true);
4370         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
4371         callback.clearSendDatagramStateChanges();
4372         sSatelliteManager.stopTransmissionUpdates(callback, getContext().getMainExecutor(),
4373                 resultListener::offer);
4374     }
4375 
sendSatelliteDatagramSuccess( boolean shouldOverridePointingUiClassName, boolean needFullScreenForPointingUi)4376     private void sendSatelliteDatagramSuccess(
4377             boolean shouldOverridePointingUiClassName, boolean needFullScreenForPointingUi) {
4378         SatelliteTransmissionUpdateCallbackTest callback = startTransmissionUpdates();
4379 
4380         // Send satellite datagram
4381         String mText = "This is a test datagram message from user";
4382         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
4383         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4384         callback.clearSendDatagramStateChanges();
4385         if (shouldOverridePointingUiClassName) {
4386             assertTrue(sMockSatelliteServiceManager.overrideSatellitePointingUiClassName());
4387         }
4388         sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
4389         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
4390         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
4391                 datagram, needFullScreenForPointingUi, getContext().getMainExecutor(),
4392                 resultListener::offer);
4393 
4394         Integer errorCode;
4395         try {
4396             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4397         } catch (InterruptedException ex) {
4398             fail("testSendSatelliteDatagram_success: Got InterruptedException in waiting"
4399                     + " for the sendDatagram result code");
4400             return;
4401         }
4402         assertNotNull(errorCode);
4403         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
4404         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
4405 
4406         /*
4407          * Send datagram transfer state should have the following transitions:
4408          * 1) IDLE to SENDING
4409          * 2) SENDING to SENDING_SUCCESS
4410          * 3) SENDING_SUCCESS to IDLE
4411          */
4412         int expectedNumOfEvents = 3;
4413         assertTrue(callback.waitUntilOnSendDatagramStateChanged(expectedNumOfEvents));
4414         assertThat(callback.getNumOfSendDatagramStateChanges()).isEqualTo(expectedNumOfEvents);
4415         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
4416                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4417                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
4418                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
4419         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
4420                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4421                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
4422                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
4423         assertThat(callback.getSendDatagramStateChange(2)).isEqualTo(
4424                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4425                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
4426                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
4427         assertTrue(sMockSatelliteServiceManager.waitForEventMockPointingUiActivityStarted(1));
4428         if (shouldOverridePointingUiClassName) {
4429             assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
4430         }
4431 
4432         callback.clearSendDatagramStateChanges();
4433         sSatelliteManager.stopTransmissionUpdates(callback, getContext().getMainExecutor(),
4434                 resultListener::offer);
4435     }
4436 
sendSatelliteDatagramDemoModeSuccess(String sampleText)4437     private void sendSatelliteDatagramDemoModeSuccess(String sampleText) {
4438         SatelliteTransmissionUpdateCallbackTest callback = startTransmissionUpdates();
4439 
4440         // Send satellite datagram
4441         SatelliteDatagram datagram = new SatelliteDatagram(sampleText.getBytes());
4442         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4443         callback.clearSendDatagramStateChanges();
4444         assertTrue(sMockSatelliteServiceManager.overrideSatellitePointingUiClassName());
4445         sMockSatelliteServiceManager.clearMockPointingUiActivityStatusChanges();
4446         sMockSatelliteServiceManager.clearSentSatelliteDatagramInfo();
4447         sSatelliteManager.setDeviceAlignedWithSatellite(true);
4448         assertTrue(sMockSatelliteServiceManager.setShouldSendDatagramToModemInDemoMode(true));
4449         sSatelliteManager.sendDatagram(SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
4450                 datagram, true, getContext().getMainExecutor(),
4451                 resultListener::offer);
4452 
4453         Integer errorCode;
4454         try {
4455             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4456         } catch (InterruptedException ex) {
4457             fail("testSendSatelliteDatagram_success: Got InterruptedException in waiting"
4458                     + " for the sendDatagram result code");
4459             return;
4460         }
4461         assertNotNull(errorCode);
4462         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
4463         assertTrue(sMockSatelliteServiceManager.waitForEventOnSendSatelliteDatagram(1));
4464 
4465         /*
4466          * Send datagram transfer state should have the following transitions:
4467          * 1) IDLE to SENDING
4468          * 2) SENDING to SENDING_SUCCESS
4469          * 3) SENDING_SUCCESS to IDLE
4470          */
4471         int expectedNumOfEvents = 3;
4472         assertTrue(callback.waitUntilOnSendDatagramStateChanged(expectedNumOfEvents));
4473         assertThat(callback.getNumOfSendDatagramStateChanges()).isEqualTo(expectedNumOfEvents);
4474         assertThat(callback.getSendDatagramStateChange(0)).isEqualTo(
4475                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4476                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SENDING,
4477                         1, SatelliteManager.SATELLITE_RESULT_SUCCESS));
4478         assertThat(callback.getSendDatagramStateChange(1)).isEqualTo(
4479                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4480                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_SEND_SUCCESS,
4481                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
4482         assertThat(callback.getSendDatagramStateChange(2)).isEqualTo(
4483                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4484                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
4485                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
4486         assertTrue(sMockSatelliteServiceManager.waitForEventMockPointingUiActivityStarted(1));
4487         assertTrue(sMockSatelliteServiceManager.restoreSatellitePointingUiClassName());
4488 
4489         sSatelliteManager.setDeviceAlignedWithSatellite(false);
4490         callback.clearSendDatagramStateChanges();
4491         sSatelliteManager.stopTransmissionUpdates(callback, getContext().getMainExecutor(),
4492                 resultListener::offer);
4493     }
4494 
moveToReceivingState()4495     private void moveToReceivingState() {
4496         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4497         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
4498                 new SatelliteTransmissionUpdateCallbackTest();
4499         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
4500                 resultListener::offer, transmissionUpdateCallback);
4501         Integer errorCode;
4502         try {
4503             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4504         } catch (InterruptedException ex) {
4505             fail("testReceiveSatelliteDatagram: Got InterruptedException in waiting"
4506                     + " for the startSatelliteTransmissionUpdates result code");
4507             return;
4508         }
4509         assertNotNull(errorCode);
4510         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
4511 
4512         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
4513         sMockSatelliteServiceManager.sendOnPendingDatagrams();
4514         assertTrue(sMockSatelliteServiceManager.waitForEventOnPollPendingSatelliteDatagrams(1));
4515 
4516         // Datagram transfer state changes from IDLE to RECEIVING.
4517         assertSingleReceiveDatagramStateChanged(transmissionUpdateCallback,
4518                 SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVING,
4519                 0, SatelliteManager.SATELLITE_RESULT_SUCCESS);
4520 
4521         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
4522         stopTransmissionUpdates(transmissionUpdateCallback);
4523     }
4524 
receiveSatelliteDatagramSuccess()4525     private void receiveSatelliteDatagramSuccess() {
4526         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
4527                 startTransmissionUpdates();
4528 
4529         SatelliteDatagramCallbackTest satelliteDatagramCallback =
4530                 new SatelliteDatagramCallbackTest();
4531         sSatelliteManager.registerForIncomingDatagram(
4532                 getContext().getMainExecutor(), satelliteDatagramCallback);
4533 
4534         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
4535         sMockSatelliteServiceManager.sendOnPendingDatagrams();
4536         assertTrue(sMockSatelliteServiceManager.waitForEventOnPollPendingSatelliteDatagrams(1));
4537 
4538         // Receive one datagram
4539         String receivedText = "This is a test datagram message from satellite";
4540         android.telephony.satellite.stub.SatelliteDatagram receivedDatagram =
4541                 new android.telephony.satellite.stub.SatelliteDatagram();
4542         receivedDatagram.data = receivedText.getBytes();
4543         sMockSatelliteServiceManager.sendOnSatelliteDatagramReceived(receivedDatagram, 0);
4544         assertTrue(satelliteDatagramCallback.waitUntilResult(1));
4545         assertArrayEquals(satelliteDatagramCallback.mDatagram.getSatelliteDatagram(),
4546                 receivedText.getBytes());
4547 
4548         // As pending count is 0, datagram transfer state changes from
4549         // IDLE -> RECEIVING -> RECEIVE_SUCCESS -> IDLE.
4550         int expectedNumOfEvents = 3;
4551         assertTrue(transmissionUpdateCallback
4552                 .waitUntilOnReceiveDatagramStateChanged(expectedNumOfEvents));
4553         assertThat(transmissionUpdateCallback.getNumOfReceiveDatagramStateChanges())
4554                 .isEqualTo(expectedNumOfEvents);
4555         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
4556                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4557                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVING,
4558                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
4559         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(1)).isEqualTo(
4560                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4561                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_RECEIVE_SUCCESS,
4562                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
4563         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(2)).isEqualTo(
4564                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4565                         SatelliteManager.SATELLITE_DATAGRAM_TRANSFER_STATE_IDLE,
4566                         0, SatelliteManager.SATELLITE_RESULT_SUCCESS));
4567 
4568         transmissionUpdateCallback.clearReceiveDatagramStateChanges();
4569         stopTransmissionUpdates(transmissionUpdateCallback);
4570         sSatelliteManager.unregisterForIncomingDatagram(satelliteDatagramCallback);
4571     }
4572 
startTransmissionUpdates()4573     private SatelliteTransmissionUpdateCallbackTest startTransmissionUpdates() {
4574         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4575         SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback =
4576                 new SatelliteTransmissionUpdateCallbackTest();
4577         sSatelliteManager.startTransmissionUpdates(getContext().getMainExecutor(),
4578                 resultListener::offer, transmissionUpdateCallback);
4579         Integer errorCode;
4580         try {
4581             errorCode = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4582         } catch (InterruptedException ex) {
4583             fail("SatelliteTransmissionUpdateCallbackTest: Got InterruptedException in waiting"
4584                     + " for the startSatelliteTransmissionUpdates result code");
4585             return null;
4586         }
4587         assertNotNull(errorCode);
4588         assertThat(errorCode).isEqualTo(SatelliteManager.SATELLITE_RESULT_SUCCESS);
4589         return transmissionUpdateCallback;
4590     }
4591 
stopTransmissionUpdates( SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback)4592     private void stopTransmissionUpdates(
4593             SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback) {
4594         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4595         sSatelliteManager.stopTransmissionUpdates(transmissionUpdateCallback,
4596                 getContext().getMainExecutor(), resultListener::offer);
4597     }
4598 
assertSingleSendDatagramStateChanged( SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback, int expectedTransferState, int expectedPendingCount, int expectedErrorCode)4599     private void assertSingleSendDatagramStateChanged(
4600             SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback,
4601             int expectedTransferState, int expectedPendingCount, int expectedErrorCode) {
4602         assertTrue(transmissionUpdateCallback.waitUntilOnSendDatagramStateChanged(1));
4603         assertThat(transmissionUpdateCallback.getNumOfSendDatagramStateChanges()).isEqualTo(1);
4604         assertThat(transmissionUpdateCallback.getSendDatagramStateChange(0)).isEqualTo(
4605                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4606                         expectedTransferState, expectedPendingCount, expectedErrorCode));
4607     }
4608 
assertSingleReceiveDatagramStateChanged( SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback, int expectedTransferState, int expectedPendingCount, int expectedErrorCode)4609     private void assertSingleReceiveDatagramStateChanged(
4610             SatelliteTransmissionUpdateCallbackTest transmissionUpdateCallback,
4611             int expectedTransferState, int expectedPendingCount, int expectedErrorCode) {
4612         assertTrue(transmissionUpdateCallback
4613                 .waitUntilOnReceiveDatagramStateChanged(1));
4614         assertThat(transmissionUpdateCallback.getNumOfReceiveDatagramStateChanges())
4615                 .isEqualTo(1);
4616         assertThat(transmissionUpdateCallback.getReceiveDatagramStateChange(0)).isEqualTo(
4617                 new SatelliteTransmissionUpdateCallbackTest.DatagramStateChangeArgument(
4618                         expectedTransferState, expectedPendingCount, expectedErrorCode));
4619     }
4620 
enforceMockModemDeveloperSetting()4621     private static void enforceMockModemDeveloperSetting() {
4622         boolean isAllowed = SystemProperties.getBoolean(ALLOW_MOCK_MODEM_PROPERTY, false);
4623         // Check for developer settings for user build. Always allow for debug builds
4624         if (!isAllowed && !DEBUG) {
4625             throw new IllegalStateException(
4626                     "!! Enable Mock Modem before running this test !! "
4627                             + "Developer options => Allow Mock Modem");
4628         }
4629     }
4630 
identifyRadiosSensitiveToSatelliteMode()4631     private void identifyRadiosSensitiveToSatelliteMode() {
4632         PackageManager packageManager = getContext().getPackageManager();
4633         List<String> satelliteModeRadiosList = new ArrayList<>();
4634         mBTWifiNFCSateReceiver = new BTWifiNFCStateReceiver();
4635         mUwbAdapterStateCallback = new UwbAdapterStateCallback();
4636         IntentFilter radioStateIntentFilter = new IntentFilter();
4637 
4638         if (packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI)) {
4639             satelliteModeRadiosList.add(Settings.Global.RADIO_WIFI);
4640             mWifiManager = getContext().getSystemService(WifiManager.class);
4641             mWifiInitState = mWifiManager.isWifiEnabled();
4642             radioStateIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
4643         }
4644 
4645         if (packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
4646             satelliteModeRadiosList.add(Settings.Global.RADIO_BLUETOOTH);
4647             mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
4648             mBTInitState = mBluetoothAdapter.isEnabled();
4649             radioStateIntentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
4650         }
4651 
4652         if (packageManager.hasSystemFeature(PackageManager.FEATURE_NFC)) {
4653             satelliteModeRadiosList.add(Settings.Global.RADIO_NFC);
4654             mNfcAdapter = NfcAdapter.getDefaultAdapter(getContext().getApplicationContext());
4655             mNfcInitState = mNfcAdapter.isEnabled();
4656             radioStateIntentFilter.addAction(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED);
4657         }
4658         getContext().registerReceiver(mBTWifiNFCSateReceiver, radioStateIntentFilter);
4659 
4660         if (packageManager.hasSystemFeature(PackageManager.FEATURE_UWB)) {
4661             satelliteModeRadiosList.add(Settings.Global.RADIO_UWB);
4662             mUwbManager = getContext().getSystemService(UwbManager.class);
4663             mUwbInitState = mUwbManager.isUwbEnabled();
4664             mUwbManager.registerAdapterStateCallback(getContext().getMainExecutor(),
4665                     mUwbAdapterStateCallback);
4666         }
4667 
4668         mTestSatelliteModeRadios = String.join(",", satelliteModeRadiosList);
4669     }
4670 
isRadioSatelliteModeSensitive(String radio)4671     private boolean isRadioSatelliteModeSensitive(String radio) {
4672         return mTestSatelliteModeRadios.contains(radio);
4673     }
4674 
areAllRadiosDisabled()4675     private boolean areAllRadiosDisabled() {
4676         logd("areAllRadiosDisabled");
4677         if (isRadioSatelliteModeSensitive(Settings.Global.RADIO_WIFI)) {
4678             assertFalse(mWifiManager.isWifiEnabled());
4679         }
4680 
4681         if (isRadioSatelliteModeSensitive(Settings.Global.RADIO_UWB)) {
4682             assertFalse(mUwbManager.isUwbEnabled());
4683         }
4684 
4685         if (isRadioSatelliteModeSensitive(Settings.Global.RADIO_NFC)) {
4686             assertFalse(mNfcAdapter.isEnabled());
4687         }
4688 
4689         if (isRadioSatelliteModeSensitive(Settings.Global.RADIO_BLUETOOTH)) {
4690             assertFalse(mBluetoothAdapter.isEnabled());
4691         }
4692 
4693         return true;
4694     }
4695 
areAllRadiosResetToInitialState()4696     private boolean areAllRadiosResetToInitialState() {
4697         logd("areAllRadiosResetToInitialState");
4698 
4699         if (mBTWifiNFCSateReceiver != null
4700                 && isRadioSatelliteModeSensitive(Settings.Global.RADIO_WIFI)) {
4701             assertTrue(mBTWifiNFCSateReceiver.waitUntilOnWifiStateChanged());
4702         }
4703 
4704         if (mBTWifiNFCSateReceiver != null
4705                 && isRadioSatelliteModeSensitive(Settings.Global.RADIO_NFC)) {
4706             assertTrue(mBTWifiNFCSateReceiver.waitUntilOnNfcStateChanged());
4707         }
4708 
4709         if (mUwbAdapterStateCallback != null
4710                 && isRadioSatelliteModeSensitive(Settings.Global.RADIO_UWB)) {
4711             assertTrue(mUwbAdapterStateCallback.waitUntilOnUwbStateChanged());
4712         }
4713 
4714         if (mBTWifiNFCSateReceiver != null
4715                 && isRadioSatelliteModeSensitive(Settings.Global.RADIO_BLUETOOTH)) {
4716             assertTrue(mBTWifiNFCSateReceiver.waitUntilOnBTStateChanged());
4717         }
4718 
4719         return true;
4720     }
4721 
setRadioExpectedState()4722     private void setRadioExpectedState() {
4723         // Set expected state of all radios to their initial states
4724         if (mBTWifiNFCSateReceiver != null) {
4725             mBTWifiNFCSateReceiver.setBTExpectedState(mBTInitState);
4726             mBTWifiNFCSateReceiver.setWifiExpectedState(mWifiInitState);
4727             mBTWifiNFCSateReceiver.setNfcExpectedState(mNfcInitState);
4728         }
4729 
4730         if (mUwbAdapterStateCallback != null) {
4731             mUwbAdapterStateCallback.setUwbExpectedState(mUwbInitState);
4732         }
4733     }
4734 
unregisterSatelliteModeRadios()4735     private void unregisterSatelliteModeRadios() {
4736         getContext().unregisterReceiver(mBTWifiNFCSateReceiver);
4737 
4738         if (isRadioSatelliteModeSensitive(Settings.Global.RADIO_UWB)) {
4739             mUwbManager.unregisterAdapterStateCallback(mUwbAdapterStateCallback);
4740         }
4741     }
4742 
requestSatelliteAttachEnabledForCarrier(boolean isEnable, int expectedResult)4743     private void requestSatelliteAttachEnabledForCarrier(boolean isEnable,
4744             int expectedResult) {
4745         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4746         sSatelliteManager.requestAttachEnabledForCarrier(sTestSubIDForCarrierSatellite,
4747                 isEnable, getContext().getMainExecutor(), resultListener::offer);
4748         Integer result;
4749         try {
4750             result = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4751         } catch (InterruptedException ex) {
4752             fail("requestAttachEnabledForCarrier failed with ex=" + ex);
4753             return;
4754         }
4755         assertNotNull(result);
4756         assertEquals(expectedResult, (int) result);
4757     }
4758 
requestAddSatelliteAttachRestrictionForCarrier(int reason, int expectedResult)4759     private void requestAddSatelliteAttachRestrictionForCarrier(int reason, int expectedResult) {
4760         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4761         sSatelliteManager.addAttachRestrictionForCarrier(sTestSubIDForCarrierSatellite,
4762                 reason, getContext().getMainExecutor(), resultListener::offer);
4763         Integer result;
4764         try {
4765             result = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4766         } catch (InterruptedException ex) {
4767             fail("requestAddSatelliteAttachRestrictionForCarrier failed with ex=" + ex);
4768             return;
4769         }
4770         assertNotNull(result);
4771         assertEquals(expectedResult, (int) result);
4772     }
4773 
verifySatelliteAttachRestrictionForCarrier(int reason, boolean isReasonExpected)4774     private void verifySatelliteAttachRestrictionForCarrier(int reason, boolean isReasonExpected) {
4775         Set<Integer> restrictionReasons = sSatelliteManager
4776                 .getAttachRestrictionReasonsForCarrier(sTestSubIDForCarrierSatellite);
4777         assertNotNull(restrictionReasons);
4778         if (isReasonExpected) {
4779             assertTrue(restrictionReasons.contains(reason));
4780         } else {
4781             assertFalse(restrictionReasons.contains(reason));
4782         }
4783     }
4784 
requestRemoveSatelliteAttachRestrictionForCarrier(int reason, int expectedResult)4785     private void requestRemoveSatelliteAttachRestrictionForCarrier(int reason, int expectedResult) {
4786         LinkedBlockingQueue<Integer> resultListener = new LinkedBlockingQueue<>(1);
4787         sSatelliteManager.removeAttachRestrictionForCarrier(sTestSubIDForCarrierSatellite,
4788                 reason, getContext().getMainExecutor(), resultListener::offer);
4789         Integer result;
4790         try {
4791             result = resultListener.poll(TIMEOUT, TimeUnit.MILLISECONDS);
4792         } catch (InterruptedException ex) {
4793             fail("requestRemoveSatelliteAttachRestrictionForCarrier failed with ex=" + ex);
4794             return;
4795         }
4796         assertNotNull(result);
4797         assertEquals(expectedResult, (int) result);
4798     }
4799 
requestIsSatelliteAttachEnabledForCarrier()4800     private Pair<Boolean, Integer> requestIsSatelliteAttachEnabledForCarrier() {
4801         final AtomicReference<Boolean> enabled = new AtomicReference<>();
4802         final AtomicReference<Integer> callback = new AtomicReference<>();
4803         CountDownLatch latch = new CountDownLatch(1);
4804         OutcomeReceiver<Boolean, SatelliteManager.SatelliteException> receiver =
4805                 new OutcomeReceiver<>() {
4806                     @Override
4807                     public void onResult(Boolean result) {
4808                         logd("onResult: result=" + result);
4809                         enabled.set(result);
4810                         latch.countDown();
4811                     }
4812 
4813                     @Override
4814                     public void onError(SatelliteManager.SatelliteException exception) {
4815                         logd("onError: onError=" + exception);
4816                         callback.set(exception.getErrorCode());
4817                         latch.countDown();
4818                     }
4819                 };
4820 
4821         sSatelliteManager.requestIsAttachEnabledForCarrier(sTestSubIDForCarrierSatellite,
4822                 getContext().getMainExecutor(), receiver);
4823         try {
4824             assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS));
4825         } catch (InterruptedException e) {
4826             fail(e.toString());
4827         }
4828         return new Pair<>(enabled.get(), callback.get());
4829     }
4830 
requestNtnSignalStrength()4831     private Pair<NtnSignalStrength, Integer> requestNtnSignalStrength() {
4832         final AtomicReference<NtnSignalStrength> ntnSignalStrength = new AtomicReference<>();
4833         final AtomicReference<Integer> callback = new AtomicReference<>();
4834         CountDownLatch latch = new CountDownLatch(1);
4835         OutcomeReceiver<NtnSignalStrength, SatelliteManager.SatelliteException> receiver =
4836                 new OutcomeReceiver<>() {
4837                     @Override
4838                     public void onResult(NtnSignalStrength result) {
4839                         logd("onResult: result=" + result);
4840                         ntnSignalStrength.set(result);
4841                         latch.countDown();
4842                     }
4843 
4844                     @Override
4845                     public void onError(SatelliteManager.SatelliteException exception) {
4846                         logd("onError: onError=" + exception);
4847                         callback.set(exception.getErrorCode());
4848                         latch.countDown();
4849                     }
4850                 };
4851 
4852         sSatelliteManager.requestNtnSignalStrength(getContext().getMainExecutor(), receiver);
4853         try {
4854             assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS));
4855         } catch (InterruptedException e) {
4856             fail(e.toString());
4857         }
4858         return new Pair<>(ntnSignalStrength.get(), callback.get());
4859     }
4860 
requestSatelliteCapabilities()4861     private Pair<SatelliteCapabilities, Integer> requestSatelliteCapabilities() {
4862         final AtomicReference<SatelliteCapabilities> SatelliteCapabilities =
4863                 new AtomicReference<>();
4864         final AtomicReference<Integer> callback = new AtomicReference<>();
4865         CountDownLatch latch = new CountDownLatch(1);
4866         OutcomeReceiver<SatelliteCapabilities, SatelliteManager.SatelliteException> receiver =
4867                 new OutcomeReceiver<>() {
4868                     @Override
4869                     public void onResult(SatelliteCapabilities result) {
4870                         logd("onResult: result=" + result);
4871                         SatelliteCapabilities.set(result);
4872                         latch.countDown();
4873                     }
4874 
4875                     @Override
4876                     public void onError(SatelliteManager.SatelliteException exception) {
4877                         logd("onError: onError=" + exception);
4878                         callback.set(exception.getErrorCode());
4879                         latch.countDown();
4880                     }
4881                 };
4882 
4883         sSatelliteManager.requestCapabilities(getContext().getMainExecutor(), receiver);
4884         try {
4885             assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS));
4886         } catch (InterruptedException e) {
4887             fail(e.toString());
4888         }
4889         return new Pair<>(SatelliteCapabilities.get(), callback.get());
4890     }
4891 
requestSessionStats()4892     private Pair<SatelliteSessionStats, Integer> requestSessionStats() {
4893         AtomicReference<SatelliteSessionStats> sessionStats = new AtomicReference<>();
4894         AtomicReference<Integer> callback = new AtomicReference<>();
4895         CountDownLatch latch = new CountDownLatch(1);
4896         OutcomeReceiver<SatelliteSessionStats, SatelliteManager.SatelliteException> receiver =
4897                 new OutcomeReceiver<SatelliteSessionStats, SatelliteManager.SatelliteException>() {
4898                     @Override
4899                     public void onResult(SatelliteSessionStats result) {
4900                         logd("requestSessionStats onResult:" + result);
4901                         sessionStats.set(result);
4902                         latch.countDown();
4903                     }
4904 
4905                     @Override
4906                     public void onError(SatelliteManager.SatelliteException exception) {
4907                         logd("requestSessionStats onError:" + exception);
4908                         callback.set(exception.getErrorCode());
4909                         latch.countDown();
4910                     }
4911 
4912                 };
4913 
4914         InstrumentationRegistry.getInstrumentation().getUiAutomation()
4915                 .adoptShellPermissionIdentity(Manifest.permission.MODIFY_PHONE_STATE,
4916                         Manifest.permission.PACKAGE_USAGE_STATS);
4917         try {
4918             sSatelliteManager.requestSessionStats(getContext().getMainExecutor(), receiver);
4919             assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS));
4920         } catch (InterruptedException e) {
4921             fail(e.toString());
4922         } finally {
4923             InstrumentationRegistry.getInstrumentation().getUiAutomation()
4924                     .dropShellPermissionIdentity();
4925             grantSatellitePermission();
4926         }
4927 
4928         return new Pair<>(sessionStats.get(), callback.get());
4929     }
4930 
requestIsSatelliteSupported()4931     private Pair<Boolean, Integer> requestIsSatelliteSupported() {
4932         final AtomicReference<Boolean> supported = new AtomicReference<>();
4933         final AtomicReference<Integer> callback = new AtomicReference<>();
4934         CountDownLatch latch = new CountDownLatch(1);
4935         OutcomeReceiver<Boolean, SatelliteManager.SatelliteException> receiver =
4936                 new OutcomeReceiver<>() {
4937                     @Override
4938                     public void onResult(Boolean result) {
4939                         logd("requestIsSatelliteSupported.onResult: result=" + result);
4940                         supported.set(result);
4941                         latch.countDown();
4942                     }
4943 
4944                     @Override
4945                     public void onError(SatelliteManager.SatelliteException exception) {
4946                         logd("requestIsSatelliteSupported.onError: onError="
4947                                 + exception.getErrorCode());
4948                         callback.set(exception.getErrorCode());
4949                         latch.countDown();
4950                     }
4951                 };
4952 
4953         sSatelliteManager.requestIsSupported(getContext().getMainExecutor(), receiver);
4954         try {
4955             assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS));
4956         } catch (InterruptedException e) {
4957             fail(e.toString());
4958         }
4959         return new Pair<>(supported.get(), callback.get());
4960     }
4961 
4962     private abstract static class BaseReceiver extends BroadcastReceiver {
4963         protected CountDownLatch mLatch = new CountDownLatch(1);
4964 
clearQueue()4965         void clearQueue() {
4966             mLatch = new CountDownLatch(1);
4967         }
4968 
waitForChanged()4969         void waitForChanged() throws Exception {
4970             mLatch.await(5000, TimeUnit.MILLISECONDS);
4971         }
4972     }
4973 
4974     private static class CarrierConfigReceiver extends BaseReceiver {
4975         private final int mSubId;
4976 
CarrierConfigReceiver(int subId)4977         CarrierConfigReceiver(int subId) {
4978             mSubId = subId;
4979         }
4980 
4981         @Override
onReceive(Context context, Intent intent)4982         public void onReceive(Context context, Intent intent) {
4983             if (CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED.equals(intent.getAction())) {
4984                 int subId = intent.getIntExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, -1);
4985                 if (mSubId == subId) {
4986                     mLatch.countDown();
4987                 }
4988             }
4989         }
4990     }
4991 
overrideCarrierConfig(int subId, PersistableBundle bundle)4992     private static void overrideCarrierConfig(int subId, PersistableBundle bundle) {
4993         try {
4994             CarrierConfigManager carrierConfigManager = InstrumentationRegistry.getInstrumentation()
4995                     .getContext().getSystemService(CarrierConfigManager.class);
4996             sCarrierConfigReceiver.clearQueue();
4997             ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(carrierConfigManager,
4998                     (m) -> m.overrideConfig(subId, bundle));
4999             sCarrierConfigReceiver.waitForChanged();
5000         } catch (Exception ex) {
5001             loge("overrideCarrierConfig(), ex=" + ex);
5002         } finally {
5003             grantSatellitePermission();
5004         }
5005     }
5006 
setSatelliteError(@atelliteManager.SatelliteResult int error)5007     private void setSatelliteError(@SatelliteManager.SatelliteResult int error) {
5008         @RadioError int satelliteError;
5009 
5010         switch(error) {
5011             case SatelliteManager.SATELLITE_RESULT_SUCCESS:
5012                 satelliteError = SatelliteResult.SATELLITE_RESULT_SUCCESS;
5013                 break;
5014             case SatelliteManager.SATELLITE_RESULT_INVALID_MODEM_STATE:
5015                 satelliteError = SatelliteResult.SATELLITE_RESULT_INVALID_MODEM_STATE;
5016                 break;
5017             case SatelliteManager.SATELLITE_RESULT_MODEM_ERROR:
5018                 satelliteError = SatelliteResult.SATELLITE_RESULT_MODEM_ERROR;
5019                 break;
5020             case SatelliteManager.SATELLITE_RESULT_RADIO_NOT_AVAILABLE:
5021                 satelliteError = SatelliteResult.SATELLITE_RESULT_RADIO_NOT_AVAILABLE;
5022                 break;
5023             case SatelliteManager.SATELLITE_RESULT_REQUEST_NOT_SUPPORTED:
5024             default:
5025                 satelliteError = SatelliteResult.SATELLITE_RESULT_REQUEST_NOT_SUPPORTED;
5026                 break;
5027         }
5028 
5029         sMockSatelliteServiceManager.setErrorCode(satelliteError);
5030     }
5031 
setNtnSignalStrength( @tnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel)5032     private void setNtnSignalStrength(
5033             @NtnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel) {
5034         sMockSatelliteServiceManager.setNtnSignalStrength(toHAL(ntnSignalStrengthLevel));
5035     }
5036 
sendOnNtnSignalStrengthChanged( @tnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel)5037     private void sendOnNtnSignalStrengthChanged(
5038             @NtnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel) {
5039         sMockSatelliteServiceManager.sendOnNtnSignalStrengthChanged(toHAL(ntnSignalStrengthLevel));
5040     }
5041 
sendOnSatelliteCapabilitiesChanged( android.telephony.satellite.stub.SatelliteCapabilities satelliteCapabilities)5042     private void sendOnSatelliteCapabilitiesChanged(
5043             android.telephony.satellite.stub.SatelliteCapabilities satelliteCapabilities) {
5044         sMockSatelliteServiceManager.sendOnSatelliteCapabilitiesChanged(satelliteCapabilities);
5045     }
5046 
sendOnSatelliteSupportedStateChanged(boolean supported)5047     private void sendOnSatelliteSupportedStateChanged(boolean supported) {
5048         sMockSatelliteServiceManager.sendOnSatelliteSupportedStateChanged(supported);
5049     }
5050 
5051     @Nullable
toHAL( @tnSignalStrength.NtnSignalStrengthLevel int signalStrengthLevelFromFramework)5052     private android.telephony.satellite.stub.NtnSignalStrength toHAL(
5053             @NtnSignalStrength.NtnSignalStrengthLevel int signalStrengthLevelFromFramework) {
5054         android.telephony.satellite.stub.NtnSignalStrength ntnSignalStrength =
5055                 new android.telephony.satellite.stub.NtnSignalStrength();
5056 
5057         switch(signalStrengthLevelFromFramework) {
5058             case NtnSignalStrength.NTN_SIGNAL_STRENGTH_NONE:
5059                 ntnSignalStrength.signalStrengthLevel = android.telephony.satellite.stub
5060                         .NtnSignalStrengthLevel.NTN_SIGNAL_STRENGTH_NONE;
5061                 break;
5062             case NtnSignalStrength.NTN_SIGNAL_STRENGTH_POOR:
5063                 ntnSignalStrength.signalStrengthLevel = android.telephony.satellite.stub
5064                         .NtnSignalStrengthLevel.NTN_SIGNAL_STRENGTH_POOR;
5065                 break;
5066             case NtnSignalStrength.NTN_SIGNAL_STRENGTH_MODERATE:
5067                 ntnSignalStrength.signalStrengthLevel = android.telephony.satellite.stub
5068                         .NtnSignalStrengthLevel.NTN_SIGNAL_STRENGTH_MODERATE;
5069                 break;
5070             case NtnSignalStrength.NTN_SIGNAL_STRENGTH_GOOD:
5071                 ntnSignalStrength.signalStrengthLevel = android.telephony.satellite.stub
5072                         .NtnSignalStrengthLevel.NTN_SIGNAL_STRENGTH_GOOD;
5073                 break;
5074             case NtnSignalStrength.NTN_SIGNAL_STRENGTH_GREAT:
5075                 ntnSignalStrength.signalStrengthLevel = android.telephony.satellite.stub
5076                         .NtnSignalStrengthLevel.NTN_SIGNAL_STRENGTH_GREAT;
5077                 break;
5078             default:
5079                 ntnSignalStrength.signalStrengthLevel = android.telephony.satellite.stub
5080                         .NtnSignalStrengthLevel.NTN_SIGNAL_STRENGTH_NONE;
5081                 break;
5082         }
5083         return ntnSignalStrength;
5084     }
5085 
getIsSatelliteEnabledForCarrierFromMockService()5086     private boolean getIsSatelliteEnabledForCarrierFromMockService() {
5087         Boolean receivedResult = sMockSatelliteServiceManager.getIsSatelliteEnabledForCarrier();
5088         return receivedResult != null ? receivedResult : false;
5089     }
5090 
getIsEmergency()5091     private boolean getIsEmergency() {
5092         Boolean receivedResult = sMockSatelliteServiceManager.getIsEmergency();
5093         return receivedResult != null ? receivedResult : false;
5094     }
5095 
clearSatelliteEnabledForCarrier()5096     private void clearSatelliteEnabledForCarrier() {
5097         sMockSatelliteServiceManager.clearSatelliteEnabledForCarrier();
5098     }
5099 
5100 
5101     static int sTestSubIDForCarrierSatellite;
5102     static SubscriptionManager sSubscriptionManager;
5103     static boolean sPreviousSatelliteAttachEnabled;
5104 
beforeSatelliteForCarrierTest()5105     private void beforeSatelliteForCarrierTest() {
5106         sTestSubIDForCarrierSatellite = getActiveSubIDForCarrierSatelliteTest();
5107         sSubscriptionManager = InstrumentationRegistry.getInstrumentation()
5108                 .getContext().getSystemService(SubscriptionManager.class);
5109         // Get the default subscription values for COLUMN_SATELLITE_ATTACH_ENABLED_FOR_CARRIER.
5110         sPreviousSatelliteAttachEnabled =
5111                 sSubscriptionManager.getBooleanSubscriptionProperty(sTestSubIDForCarrierSatellite,
5112                         SubscriptionManager.SATELLITE_ATTACH_ENABLED_FOR_CARRIER,
5113                         false,
5114                         getContext());
5115         UiAutomation ui = InstrumentationRegistry.getInstrumentation().getUiAutomation();
5116         try {
5117             ui.adoptShellPermissionIdentity();
5118             // Set user Setting as false
5119             sSubscriptionManager.setSubscriptionProperty(sTestSubIDForCarrierSatellite,
5120                     SubscriptionManager.SATELLITE_ATTACH_ENABLED_FOR_CARRIER, String.valueOf(0));
5121         } finally {
5122             ui.dropShellPermissionIdentity();
5123         }
5124     }
5125 
afterSatelliteForCarrierTest()5126     private void afterSatelliteForCarrierTest() {
5127         // Set user Setting value to previous one.
5128         UiAutomation ui = InstrumentationRegistry.getInstrumentation().getUiAutomation();
5129         try {
5130             ui.adoptShellPermissionIdentity();
5131             sSubscriptionManager.setSubscriptionProperty(sTestSubIDForCarrierSatellite,
5132                     SubscriptionManager.SATELLITE_ATTACH_ENABLED_FOR_CARRIER,
5133                     sPreviousSatelliteAttachEnabled ? "1" : "0");
5134         } finally {
5135             ui.dropShellPermissionIdentity();
5136             sTestSubIDForCarrierSatellite = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
5137         }
5138     }
5139 
updateSupportedRadioTechnologies( @onNull int[] supportedRadioTechnologies, boolean needSetUp)5140     private void updateSupportedRadioTechnologies(
5141             @NonNull int[] supportedRadioTechnologies, boolean needSetUp) {
5142         logd("updateSupportedRadioTechnologies: supportedRadioTechnologies="
5143                 + supportedRadioTechnologies[0]);
5144         grantSatellitePermission();
5145 
5146         SatelliteModemStateCallbackTest callback = new SatelliteModemStateCallbackTest();
5147         long registerResult = sSatelliteManager.registerForModemStateChanged(
5148                 getContext().getMainExecutor(), callback);
5149         assertEquals(SatelliteManager.SATELLITE_RESULT_SUCCESS, registerResult);
5150         assertTrue(callback.waitUntilResult(1));
5151 
5152         assertTrue(sMockSatelliteServiceManager.restoreSatelliteServicePackageName());
5153         waitFor(2000);
5154         sSatelliteManager.unregisterForModemStateChanged(callback);
5155         sMockSatelliteServiceManager.setSupportedRadioTechnologies(supportedRadioTechnologies);
5156         try {
5157             setupMockSatelliteService();
5158             if (needSetUp) {
5159                 setUp();
5160             }
5161         } catch (Exception e) {
5162             loge("Fail to set up mock satellite service after updating supported radio "
5163                     + "technologies, e=" + e);
5164         }
5165 
5166         revokeSatellitePermission();
5167     }
5168 
requestIsCommunicationAllowedForCurrentLocation()5169     private Pair<Boolean, Integer> requestIsCommunicationAllowedForCurrentLocation() {
5170         final AtomicReference<Boolean> enabled = new AtomicReference<>();
5171         final AtomicReference<Integer> callback = new AtomicReference<>();
5172         CountDownLatch latch = new CountDownLatch(1);
5173         OutcomeReceiver<Boolean, SatelliteManager.SatelliteException> receiver =
5174                 new OutcomeReceiver<>() {
5175                     @Override
5176                     public void onResult(Boolean result) {
5177                         logd("isSatelliteAllowed.onResult: result=" + result);
5178                         enabled.set(result);
5179                         latch.countDown();
5180                     }
5181 
5182                     @Override
5183                     public void onError(SatelliteManager.SatelliteException exception) {
5184                         logd("isSatelliteAllowed.onError: onError=" + exception);
5185                         callback.set(exception.getErrorCode());
5186                         latch.countDown();
5187                     }
5188                 };
5189 
5190         sSatelliteManager.requestIsCommunicationAllowedForCurrentLocation(
5191                 getContext().getMainExecutor(), receiver);
5192         try {
5193             assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS));
5194         } catch (InterruptedException e) {
5195             fail("isSatelliteAllowed: ex=" + e);
5196         }
5197         return new Pair<>(enabled.get(), callback.get());
5198     }
5199 
verifyIsSatelliteAllowed(boolean allowed)5200     private void verifyIsSatelliteAllowed(boolean allowed) {
5201         grantSatellitePermission();
5202         Pair<Boolean, Integer> result =
5203                 requestIsCommunicationAllowedForCurrentLocation();
5204         assertNotNull(result.first);
5205         assertEquals(allowed, result.first);
5206     }
5207 
registerTestLocationProvider()5208     private static void registerTestLocationProvider() {
5209         requestMockLocationPermission(true);
5210         sLocationManager.addTestProvider(TEST_PROVIDER,
5211                 new ProviderProperties.Builder().build());
5212         sLocationManager.setTestProviderEnabled(TEST_PROVIDER, true);
5213     }
5214 
unregisterTestLocationProvider()5215     private static void unregisterTestLocationProvider() {
5216         requestMockLocationPermission(true);
5217         sLocationManager.removeTestProvider(TEST_PROVIDER);
5218         requestMockLocationPermission(false);
5219     }
5220 
setTestProviderLocation(double latitude, double longitude)5221     private void setTestProviderLocation(double latitude, double longitude) {
5222         requestMockLocationPermission(true);
5223         Location loc = LocationUtils.createLocation(
5224                 TEST_PROVIDER, latitude, longitude, LOCATION_ACCURACY);
5225         sLocationManager.setTestProviderLocation(TEST_PROVIDER, loc);
5226     }
5227 
requestMockLocationPermission(boolean allowed)5228     private static void requestMockLocationPermission(boolean allowed) {
5229         AppOpsManager aom = getContext().getSystemService(AppOpsManager.class);
5230         ShellIdentityUtils.invokeMethodWithShellPermissionsNoReturn(aom, (appOpsMan) -> appOpsMan
5231                 .setUidMode(AppOpsManager.OPSTR_MOCK_LOCATION, Process.myUid(),
5232                         allowed ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_ERRORED));
5233     }
5234 
setUpSatelliteAccessAllowed()5235     private static void setUpSatelliteAccessAllowed() {
5236         logd("setUpSatelliteAccessAllowed...");
5237         assertTrue(sMockSatelliteServiceManager.setCountryCodes(false,
5238                 OVERRIDING_COUNTRY_CODES, null, null, 0));
5239         assertTrue(sMockSatelliteServiceManager.setSatelliteAccessControlOverlayConfigs(
5240                 false, true, null, 0, SATELLITE_COUNTRY_CODES));
5241     }
5242 
resetSatelliteAccessControlOverlayConfigs()5243     private static void resetSatelliteAccessControlOverlayConfigs() {
5244         logd("resetSatelliteAccessControlOverlayConfigs");
5245         assertTrue(sMockSatelliteServiceManager.setCountryCodes(true, null, null, null, 0));
5246         assertTrue(sMockSatelliteServiceManager.setSatelliteAccessControlOverlayConfigs(
5247                 true, true, null, 0, null));
5248     }
5249 }
5250