• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 com.android.internal.telephony.satellite;
18 
19 import static android.hardware.devicestate.DeviceState.PROPERTY_FOLDABLE_DISPLAY_CONFIGURATION_INNER_PRIMARY;
20 import static android.hardware.devicestate.DeviceState.PROPERTY_FOLDABLE_DISPLAY_CONFIGURATION_OUTER_PRIMARY;
21 import static android.hardware.devicestate.DeviceState.PROPERTY_FOLDABLE_HARDWARE_CONFIGURATION_FOLD_IN_CLOSED;
22 import static android.hardware.devicestate.DeviceState.PROPERTY_FOLDABLE_HARDWARE_CONFIGURATION_FOLD_IN_OPEN;
23 import static android.hardware.devicestate.feature.flags.Flags.FLAG_DEVICE_STATE_PROPERTY_MIGRATION;
24 import static android.telephony.CarrierConfigManager.CARRIER_ROAMING_NTN_CONNECT_AUTOMATIC;
25 import static android.telephony.CarrierConfigManager.CARRIER_ROAMING_NTN_CONNECT_MANUAL;
26 import static android.telephony.CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL;
27 import static android.telephony.CarrierConfigManager.KEY_CARRIER_ROAMING_NTN_CONNECT_TYPE_INT;
28 import static android.telephony.CarrierConfigManager.KEY_CARRIER_SUPPORTED_SATELLITE_NOTIFICATION_HYSTERESIS_SEC_INT;
29 import static android.telephony.CarrierConfigManager.KEY_EMERGENCY_CALL_TO_SATELLITE_T911_HANDOVER_TIMEOUT_MILLIS_INT;
30 import static android.telephony.CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL;
31 import static android.telephony.CarrierConfigManager.KEY_SATELLITE_CONNECTION_HYSTERESIS_SEC_INT;
32 import static android.telephony.CarrierConfigManager.KEY_SATELLITE_ESOS_SUPPORTED_BOOL;
33 import static android.telephony.CarrierConfigManager.KEY_SATELLITE_NIDD_APN_NAME_STRING;
34 import static android.telephony.CarrierConfigManager.KEY_SATELLITE_ROAMING_P2P_SMS_SUPPORTED_BOOL;
35 import static android.telephony.CarrierConfigManager.KEY_SATELLITE_ROAMING_TURN_OFF_SESSION_FOR_EMERGENCY_CALL_BOOL;
36 import static android.telephony.CarrierConfigManager.SATELLITE_DATA_SUPPORT_ALL;
37 import static android.telephony.CarrierConfigManager.SATELLITE_DATA_SUPPORT_BANDWIDTH_CONSTRAINED;
38 import static android.telephony.CarrierConfigManager.SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED;
39 import static android.telephony.NetworkRegistrationInfo.SERVICE_TYPE_DATA;
40 import static android.telephony.NetworkRegistrationInfo.SERVICE_TYPE_MMS;
41 import static android.telephony.NetworkRegistrationInfo.SERVICE_TYPE_SMS;
42 import static android.telephony.NetworkRegistrationInfo.SERVICE_TYPE_VOICE;
43 import static android.telephony.SubscriptionManager.SATELLITE_ENTITLEMENT_STATUS;
44 import static android.telephony.satellite.NtnSignalStrength.NTN_SIGNAL_STRENGTH_GOOD;
45 import static android.telephony.satellite.NtnSignalStrength.NTN_SIGNAL_STRENGTH_GREAT;
46 import static android.telephony.satellite.NtnSignalStrength.NTN_SIGNAL_STRENGTH_NONE;
47 import static android.telephony.satellite.NtnSignalStrength.NTN_SIGNAL_STRENGTH_POOR;
48 import static android.telephony.satellite.SatelliteManager.KEY_DEMO_MODE_ENABLED;
49 import static android.telephony.satellite.SatelliteManager.KEY_DEPROVISION_SATELLITE_TOKENS;
50 import static android.telephony.satellite.SatelliteManager.KEY_EMERGENCY_MODE_ENABLED;
51 import static android.telephony.satellite.SatelliteManager.KEY_NTN_SIGNAL_STRENGTH;
52 import static android.telephony.satellite.SatelliteManager.KEY_PROVISION_SATELLITE_TOKENS;
53 import static android.telephony.satellite.SatelliteManager.KEY_REQUEST_PROVISION_SUBSCRIBER_ID_TOKEN;
54 import static android.telephony.satellite.SatelliteManager.KEY_SATELLITE_CAPABILITIES;
55 import static android.telephony.satellite.SatelliteManager.KEY_SATELLITE_COMMUNICATION_ALLOWED;
56 import static android.telephony.satellite.SatelliteManager.KEY_SATELLITE_ENABLED;
57 import static android.telephony.satellite.SatelliteManager.KEY_SATELLITE_NEXT_VISIBILITY;
58 import static android.telephony.satellite.SatelliteManager.KEY_SATELLITE_PROVISIONED;
59 import static android.telephony.satellite.SatelliteManager.KEY_SATELLITE_SUPPORTED;
60 import static android.telephony.satellite.SatelliteManager.METADATA_SATELLITE_MANUAL_CONNECT_P2P_SUPPORT;
61 import static android.telephony.satellite.SatelliteManager.NT_RADIO_TECHNOLOGY_EMTC_NTN;
62 import static android.telephony.satellite.SatelliteManager.NT_RADIO_TECHNOLOGY_NB_IOT_NTN;
63 import static android.telephony.satellite.SatelliteManager.NT_RADIO_TECHNOLOGY_NR_NTN;
64 import static android.telephony.satellite.SatelliteManager.NT_RADIO_TECHNOLOGY_PROPRIETARY;
65 import static android.telephony.satellite.SatelliteManager.SATELLITE_COMMUNICATION_RESTRICTION_REASON_ENTITLEMENT;
66 import static android.telephony.satellite.SatelliteManager.SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION;
67 import static android.telephony.satellite.SatelliteManager.SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER;
68 import static android.telephony.satellite.SatelliteManager.SATELLITE_MODEM_STATE_CONNECTED;
69 import static android.telephony.satellite.SatelliteManager.SATELLITE_MODEM_STATE_NOT_CONNECTED;
70 import static android.telephony.satellite.SatelliteManager.SATELLITE_MODEM_STATE_OFF;
71 import static android.telephony.satellite.SatelliteManager.SATELLITE_MODEM_STATE_UNAVAILABLE;
72 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_DISABLE_IN_PROGRESS;
73 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_EMERGENCY_CALL_IN_PROGRESS;
74 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_ERROR;
75 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_INVALID_ARGUMENTS;
76 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_INVALID_MODEM_STATE;
77 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_INVALID_TELEPHONY_STATE;
78 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_MODEM_TIMEOUT;
79 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_NOT_SUPPORTED;
80 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_NO_RESOURCES;
81 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_RADIO_NOT_AVAILABLE;
82 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_REQUEST_ABORTED;
83 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_REQUEST_IN_PROGRESS;
84 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_REQUEST_NOT_SUPPORTED;
85 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_SERVICE_NOT_PROVISIONED;
86 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_SERVICE_PROVISION_IN_PROGRESS;
87 import static android.telephony.satellite.SatelliteManager.SATELLITE_RESULT_SUCCESS;
88 
89 import static com.android.internal.telephony.satellite.SatelliteController.DEFAULT_CARRIER_EMERGENCY_CALL_WAIT_FOR_CONNECTION_TIMEOUT_MILLIS;
90 import static com.android.internal.telephony.satellite.SatelliteController.SATELLITE_DATA_PLAN_METERED;
91 import static com.android.internal.telephony.satellite.SatelliteController.SATELLITE_DATA_PLAN_UNMETERED;
92 import static com.android.internal.telephony.satellite.SatelliteController.SATELLITE_MODE_ENABLED_FALSE;
93 import static com.android.internal.telephony.satellite.SatelliteController.SATELLITE_MODE_ENABLED_TRUE;
94 
95 import static org.junit.Assert.assertArrayEquals;
96 import static org.junit.Assert.assertEquals;
97 import static org.junit.Assert.assertFalse;
98 import static org.junit.Assert.assertNotEquals;
99 import static org.junit.Assert.assertNotNull;
100 import static org.junit.Assert.assertNull;
101 import static org.junit.Assert.assertThrows;
102 import static org.junit.Assert.assertTrue;
103 import static org.junit.Assert.fail;
104 import static org.mockito.ArgumentMatchers.any;
105 import static org.mockito.ArgumentMatchers.anyBoolean;
106 import static org.mockito.ArgumentMatchers.anyInt;
107 import static org.mockito.ArgumentMatchers.anyList;
108 import static org.mockito.ArgumentMatchers.anyLong;
109 import static org.mockito.ArgumentMatchers.anyString;
110 import static org.mockito.ArgumentMatchers.eq;
111 import static org.mockito.Mockito.atLeastOnce;
112 import static org.mockito.Mockito.clearInvocations;
113 import static org.mockito.Mockito.doAnswer;
114 import static org.mockito.Mockito.doNothing;
115 import static org.mockito.Mockito.doReturn;
116 import static org.mockito.Mockito.mock;
117 import static org.mockito.Mockito.never;
118 import static org.mockito.Mockito.reset;
119 import static org.mockito.Mockito.times;
120 import static org.mockito.Mockito.verify;
121 import static org.mockito.Mockito.when;
122 
123 import android.annotation.NonNull;
124 import android.annotation.Nullable;
125 import android.app.NotificationManager;
126 import android.app.usage.NetworkStatsManager;
127 import android.content.BroadcastReceiver;
128 import android.content.Context;
129 import android.content.Intent;
130 import android.content.IntentFilter;
131 import android.content.SharedPreferences;
132 import android.content.pm.ApplicationInfo;
133 import android.content.pm.PackageManager;
134 import android.content.res.Resources;
135 import android.hardware.devicestate.DeviceState;
136 import android.location.LocationManager;
137 import android.net.Uri;
138 import android.os.AsyncResult;
139 import android.os.Bundle;
140 import android.os.CancellationSignal;
141 import android.os.Handler;
142 import android.os.ICancellationSignal;
143 import android.os.Looper;
144 import android.os.Message;
145 import android.os.OutcomeReceiver;
146 import android.os.PersistableBundle;
147 import android.os.RemoteException;
148 import android.os.ResultReceiver;
149 import android.platform.test.annotations.RequiresFlagsDisabled;
150 import android.platform.test.annotations.RequiresFlagsEnabled;
151 import android.platform.test.flag.junit.CheckFlagsRule;
152 import android.platform.test.flag.junit.DeviceFlagsValueProvider;
153 import android.telephony.AccessNetworkConstants;
154 import android.telephony.CarrierConfigManager;
155 import android.telephony.CellSignalStrength;
156 import android.telephony.NetworkRegistrationInfo;
157 import android.telephony.Rlog;
158 import android.telephony.ServiceState;
159 import android.telephony.SignalStrength;
160 import android.telephony.SubscriptionInfo;
161 import android.telephony.SubscriptionManager;
162 import android.telephony.satellite.EarfcnRange;
163 import android.telephony.satellite.INtnSignalStrengthCallback;
164 import android.telephony.satellite.ISatelliteCapabilitiesCallback;
165 import android.telephony.satellite.ISatelliteDatagramCallback;
166 import android.telephony.satellite.ISatelliteModemStateCallback;
167 import android.telephony.satellite.ISatelliteProvisionStateCallback;
168 import android.telephony.satellite.ISatelliteTransmissionUpdateCallback;
169 import android.telephony.satellite.ISelectedNbIotSatelliteSubscriptionCallback;
170 import android.telephony.satellite.NtnSignalStrength;
171 import android.telephony.satellite.SatelliteCapabilities;
172 import android.telephony.satellite.SatelliteDatagram;
173 import android.telephony.satellite.SatelliteInfo;
174 import android.telephony.satellite.SatelliteManager;
175 import android.telephony.satellite.SatelliteManager.SatelliteException;
176 import android.telephony.satellite.SatelliteModemEnableRequestAttributes;
177 import android.telephony.satellite.SatellitePosition;
178 import android.telephony.satellite.SatelliteSubscriberInfo;
179 import android.telephony.satellite.SatelliteSubscriberProvisionStatus;
180 import android.telephony.satellite.SatelliteSubscriptionInfo;
181 import android.telephony.satellite.SystemSelectionSpecifier;
182 import android.testing.AndroidTestingRunner;
183 import android.testing.TestableLooper;
184 import android.util.IntArray;
185 import android.util.Pair;
186 import android.util.SparseArray;
187 import android.util.SparseBooleanArray;
188 
189 import com.android.internal.R;
190 import com.android.internal.telephony.IBooleanConsumer;
191 import com.android.internal.telephony.IIntegerConsumer;
192 import com.android.internal.telephony.IVoidConsumer;
193 import com.android.internal.telephony.Phone;
194 import com.android.internal.telephony.PhoneFactory;
195 import com.android.internal.telephony.TelephonyTest;
196 import com.android.internal.telephony.configupdate.ConfigProviderAdaptor;
197 import com.android.internal.telephony.configupdate.TelephonyConfigUpdateInstallReceiver;
198 import com.android.internal.telephony.flags.FeatureFlags;
199 import com.android.internal.telephony.satellite.metrics.ControllerMetricsStats;
200 import com.android.internal.telephony.satellite.metrics.ProvisionMetricsStats;
201 import com.android.internal.telephony.satellite.metrics.SessionMetricsStats;
202 import com.android.internal.telephony.subscription.SubscriptionInfoInternal;
203 import com.android.internal.telephony.subscription.SubscriptionManagerService;
204 
205 import org.junit.After;
206 import org.junit.Before;
207 import org.junit.Rule;
208 import org.junit.Test;
209 import org.junit.runner.RunWith;
210 import org.mockito.ArgumentCaptor;
211 import org.mockito.ArgumentMatchers;
212 import org.mockito.Mock;
213 import org.mockito.MockitoAnnotations;
214 
215 import java.lang.reflect.Field;
216 import java.util.ArrayList;
217 import java.util.Arrays;
218 import java.util.HashMap;
219 import java.util.HashSet;
220 import java.util.List;
221 import java.util.Map;
222 import java.util.Optional;
223 import java.util.Set;
224 import java.util.UUID;
225 import java.util.concurrent.CountDownLatch;
226 import java.util.concurrent.Executor;
227 import java.util.concurrent.Semaphore;
228 import java.util.concurrent.TimeUnit;
229 import java.util.stream.Collectors;
230 
231 @RunWith(AndroidTestingRunner.class)
232 @TestableLooper.RunWithLooper
233 public class SatelliteControllerTest extends TelephonyTest {
234     private static final String TAG = "SatelliteControllerTest";
235 
236     private static final long TIMEOUT = 500;
237     private static final int SUB_ID = 0;
238     private static final int SUB_ID1 = 1;
239     private static final int MAX_BYTES_PER_OUT_GOING_DATAGRAM = 339;
240     private static final String TEST_SATELLITE_TOKEN = "TEST_SATELLITE_TOKEN";
241     private static final String TEST_NEXT_SATELLITE_TOKEN = "TEST_NEXT_SATELLITE_TOKEN";
242     private static final String[] EMPTY_STRING_ARRAY = {};
243     private static final List<String> EMPTY_STRING_LIST = new ArrayList<>();
244     private static final String SATELLITE_SYSTEM_NOTIFICATION_DONE_KEY =
245             "satellite_system_notification_done_key";
246     private static final int[] ACTIVE_SUB_IDS = {SUB_ID};
247     private static final int TEST_WAIT_FOR_SATELLITE_ENABLING_RESPONSE_TIMEOUT_MILLIS =
248             (int) TimeUnit.SECONDS.toMillis(60);
249     private static final int TEST_WAIT_FOR_CELLULAR_MODEM_OFF_TIMEOUT_MILLIS =
250             (int) TimeUnit.SECONDS.toMillis(60);
251     private static final Set<String> TEST_ALL_SATELLITE_PLMN_SET = new HashSet<>(
252             Arrays.asList("310830", "313210"));
253 
254 
255     private static final String SATELLITE_PLMN = "00103";
256     private List<Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener>>
257             mCarrierConfigChangedListenerList = new ArrayList<>();
258 
259     private TestSatelliteController mSatelliteControllerUT;
260     private TestSharedPreferences mSharedPreferences;
261     private PersistableBundle mCarrierConfigBundle;
262     private ServiceState mServiceState2;
263 
264     private SubscriptionInfo testSubscriptionInfo;
265     private SubscriptionInfo testSubscriptionInfo2;
266 
267     @Mock private TestSatelliteController mMockSatelliteController;
268     @Mock private DatagramController mMockDatagramController;
269     @Mock private SatelliteModemInterface mMockSatelliteModemInterface;
270     @Mock private SatelliteSessionController mMockSatelliteSessionController;
271     @Mock private PointingAppController mMockPointingAppController;
272     @Mock private ControllerMetricsStats mMockControllerMetricsStats;
273     @Mock private ProvisionMetricsStats mMockProvisionMetricsStats;
274     @Mock private SessionMetricsStats mMockSessionMetricsStats;
275     @Mock private SubscriptionManagerService mMockSubscriptionManagerService;
276     @Mock private NotificationManager mMockNotificationManager;
277     private List<Integer> mIIntegerConsumerResults =  new ArrayList<>();
278     @Mock private ISatelliteTransmissionUpdateCallback mStartTransmissionUpdateCallback;
279     @Mock private ISatelliteTransmissionUpdateCallback mStopTransmissionUpdateCallback;
280     @Mock private FeatureFlags mFeatureFlags;
281     @Mock private TelephonyConfigUpdateInstallReceiver mMockTelephonyConfigUpdateInstallReceiver;
282     @Mock private SatelliteConfigParser mMockConfigParser;
283     @Mock private CellSignalStrength mCellSignalStrength;
284     @Mock private SatelliteConfig mMockConfig;
285     @Mock private DemoSimulator mMockDemoSimulator;
286     @Mock private Resources mResources;
287     @Mock private SubscriptionManager mSubscriptionManager;
288     @Mock private SubscriptionInfo mSubscriptionInfo;
289     @Mock private PackageManager mMockPManager;
290     @Mock private Intent mMockLocationIntent;
291 
292     private Semaphore mIIntegerConsumerSemaphore = new Semaphore(0);
293     private IIntegerConsumer mIIntegerConsumer = new IIntegerConsumer.Stub() {
294         @Override
295         public void accept(int result) {
296             logd("mIIntegerConsumer: result=" + result);
297             mIIntegerConsumerResults.add(result);
298             try {
299                 mIIntegerConsumerSemaphore.release();
300             } catch (Exception ex) {
301                 loge("mIIntegerConsumer: Got exception in releasing semaphore, ex=" + ex);
302             }
303         }
304     };
305 
306     private boolean mIsSatelliteServiceSupported = true;
307     private boolean mIsPointingRequired = true;
308     private Set<Integer> mSupportedRadioTechnologies = new HashSet<>(Arrays.asList(
309             NT_RADIO_TECHNOLOGY_NR_NTN,
310             NT_RADIO_TECHNOLOGY_EMTC_NTN,
311             NT_RADIO_TECHNOLOGY_NB_IOT_NTN,
312             NT_RADIO_TECHNOLOGY_PROPRIETARY));
313     private SatelliteCapabilities mSatelliteCapabilities = new SatelliteCapabilities(
314             mSupportedRadioTechnologies, mIsPointingRequired, MAX_BYTES_PER_OUT_GOING_DATAGRAM,
315             new HashMap<>());
316     private SatelliteCapabilities mEmptySatelliteCapabilities = new SatelliteCapabilities(
317             new HashSet<>(), mIsPointingRequired, MAX_BYTES_PER_OUT_GOING_DATAGRAM,
318             new HashMap<>());
319     final int mCarrierId = 0;
320     final String mImsi = "1234567890123";
321     final String mNiddApn = "testApn";
322     final String mMsisdn = "0987654321";
323     final String mSubscriberId = mImsi.substring(0, 6) + mMsisdn;
324     final String mIccId = "1000000000000001";
325     final String mIccId2 = "2000000000000002";
326     final String mImsi2 = "2345678901234";
327     final String mMsisdn2 = "9876543210";
328     final String mSubscriberId2 = mIccId2;
329 
330     private Semaphore mSatelliteCapabilitiesSemaphore = new Semaphore(0);
331     private SatelliteCapabilities mQueriedSatelliteCapabilities = null;
332     private int mQueriedSatelliteCapabilitiesResultCode = SATELLITE_RESULT_SUCCESS;
333     private ResultReceiver mSatelliteCapabilitiesReceiver = new ResultReceiver(null) {
334         @Override
335         protected void onReceiveResult(int resultCode, Bundle resultData) {
336             mQueriedSatelliteCapabilitiesResultCode = resultCode;
337             logd("mSatelliteCapabilitiesReceiver: resultCode=" + resultCode);
338             if (resultCode == SATELLITE_RESULT_SUCCESS) {
339                 if (resultData.containsKey(KEY_SATELLITE_CAPABILITIES)) {
340                     mQueriedSatelliteCapabilities = resultData.getParcelable(
341                             KEY_SATELLITE_CAPABILITIES, SatelliteCapabilities.class);
342                 } else {
343                     loge("KEY_SATELLITE_SUPPORTED does not exist.");
344                     mQueriedSatelliteCapabilities = null;
345                 }
346             } else {
347                 mQueriedSatelliteCapabilities = null;
348             }
349             try {
350                 mSatelliteCapabilitiesSemaphore.release();
351             } catch (Exception ex) {
352                 loge("mSatelliteCapabilitiesReceiver: Got exception in releasing semaphore, ex="
353                         + ex);
354             }
355         }
356     };
357 
358     private boolean mQueriedSatelliteSupported = false;
359     private int mQueriedSatelliteSupportedResultCode = SATELLITE_RESULT_SUCCESS;
360     private Semaphore mSatelliteSupportSemaphore = new Semaphore(0);
361     private ResultReceiver mSatelliteSupportReceiver = new ResultReceiver(null) {
362         @Override
363         protected void onReceiveResult(int resultCode, Bundle resultData) {
364             mQueriedSatelliteSupportedResultCode = resultCode;
365             logd("mSatelliteSupportReceiver: resultCode=" + resultCode);
366             if (resultCode == SATELLITE_RESULT_SUCCESS) {
367                 if (resultData.containsKey(KEY_SATELLITE_SUPPORTED)) {
368                     mQueriedSatelliteSupported = resultData.getBoolean(KEY_SATELLITE_SUPPORTED);
369                 } else {
370                     loge("KEY_SATELLITE_SUPPORTED does not exist.");
371                     mQueriedSatelliteSupported = false;
372                 }
373             } else {
374                 mQueriedSatelliteSupported = false;
375             }
376             try {
377                 mSatelliteSupportSemaphore.release();
378             } catch (Exception ex) {
379                 loge("mSatelliteSupportReceiver: Got exception in releasing semaphore, ex=" + ex);
380             }
381         }
382     };
383 
384     private boolean mQueriedIsSatelliteEnabled = false;
385     private int mQueriedIsSatelliteEnabledResultCode = SATELLITE_RESULT_SUCCESS;
386     private Semaphore mIsSatelliteEnabledSemaphore = new Semaphore(0);
387     private ResultReceiver mIsSatelliteEnabledReceiver = new ResultReceiver(null) {
388         @Override
389         protected void onReceiveResult(int resultCode, Bundle resultData) {
390             logd("mIsSatelliteEnabledReceiver: resultCode=" + resultCode);
391             mQueriedIsSatelliteEnabledResultCode = resultCode;
392             if (resultCode == SATELLITE_RESULT_SUCCESS) {
393                 if (resultData.containsKey(KEY_SATELLITE_ENABLED)) {
394                     mQueriedIsSatelliteEnabled = resultData.getBoolean(KEY_SATELLITE_ENABLED);
395                 } else {
396                     loge("KEY_SATELLITE_ENABLED does not exist.");
397                     mQueriedIsSatelliteEnabled = false;
398                 }
399             } else {
400                 mQueriedIsSatelliteEnabled = false;
401             }
402             try {
403                 mIsSatelliteEnabledSemaphore.release();
404             } catch (Exception ex) {
405                 loge("mIsSatelliteEnabledReceiver: Got exception in releasing semaphore, ex=" + ex);
406             }
407         }
408     };
409 
410     private boolean mQueriedIsDemoModeEnabled = false;
411     private int mQueriedIsDemoModeEnabledResultCode = SATELLITE_RESULT_SUCCESS;
412     private Semaphore mIsDemoModeEnabledSemaphore = new Semaphore(0);
413     private ResultReceiver mIsDemoModeEnabledReceiver = new ResultReceiver(null) {
414         @Override
415         protected void onReceiveResult(int resultCode, Bundle resultData) {
416             mQueriedIsDemoModeEnabledResultCode = resultCode;
417             logd("mIsDemoModeEnabledReceiver: resultCode=" + resultCode);
418             if (resultCode == SATELLITE_RESULT_SUCCESS) {
419                 if (resultData.containsKey(KEY_DEMO_MODE_ENABLED)) {
420                     mQueriedIsDemoModeEnabled = resultData.getBoolean(KEY_DEMO_MODE_ENABLED);
421                 } else {
422                     loge("KEY_DEMO_MODE_ENABLED does not exist.");
423                     mQueriedIsDemoModeEnabled = false;
424                 }
425             } else {
426                 mQueriedIsDemoModeEnabled = false;
427             }
428             try {
429                 mIsDemoModeEnabledSemaphore.release();
430             } catch (Exception ex) {
431                 loge("mIsDemoModeEnabledReceiver: Got exception in releasing semaphore, ex=" + ex);
432             }
433         }
434     };
435 
436     private boolean mQueriedIsSatelliteProvisioned = false;
437     private int mQueriedIsSatelliteProvisionedResultCode = SATELLITE_RESULT_SUCCESS;
438     private Semaphore mIsSatelliteProvisionedSemaphore = new Semaphore(0);
439     private ResultReceiver mIsSatelliteProvisionedReceiver = new ResultReceiver(null) {
440         @Override
441         protected void onReceiveResult(int resultCode, Bundle resultData) {
442             mQueriedIsSatelliteProvisionedResultCode = resultCode;
443             logd("mIsSatelliteProvisionedReceiver: resultCode=" + resultCode);
444             if (resultCode == SATELLITE_RESULT_SUCCESS) {
445                 if (resultData.containsKey(KEY_SATELLITE_PROVISIONED)) {
446                     mQueriedIsSatelliteProvisioned =
447                             resultData.getBoolean(KEY_SATELLITE_PROVISIONED);
448                 } else {
449                     loge("KEY_SATELLITE_PROVISIONED does not exist.");
450                     mQueriedIsSatelliteProvisioned = false;
451                 }
452             } else {
453                 mQueriedIsSatelliteProvisioned = false;
454             }
455             try {
456                 mIsSatelliteProvisionedSemaphore.release();
457             } catch (Exception ex) {
458                 loge("mIsSatelliteProvisionedReceiver: Got exception in releasing semaphore ex="
459                         + ex);
460             }
461         }
462     };
463 
464     private boolean mQueriedSatelliteAllowed = false;
465     private int mQueriedSatelliteAllowedResultCode = SATELLITE_RESULT_SUCCESS;
466     private Semaphore mSatelliteAllowedSemaphore = new Semaphore(0);
467     private ResultReceiver mSatelliteAllowedReceiver = new ResultReceiver(null) {
468         @Override
469         protected void onReceiveResult(int resultCode, Bundle resultData) {
470             mQueriedSatelliteAllowedResultCode = resultCode;
471             logd("mSatelliteAllowedReceiver: resultCode=" + resultCode);
472             if (resultCode == SATELLITE_RESULT_SUCCESS) {
473                 if (resultData.containsKey(KEY_SATELLITE_COMMUNICATION_ALLOWED)) {
474                     mQueriedSatelliteAllowed = resultData.getBoolean(
475                             KEY_SATELLITE_COMMUNICATION_ALLOWED);
476                 } else {
477                     loge("KEY_SATELLITE_COMMUNICATION_ALLOWED does not exist.");
478                     mQueriedSatelliteAllowed = false;
479                 }
480             } else {
481                 mQueriedSatelliteAllowed = false;
482             }
483             try {
484                 mSatelliteAllowedSemaphore.release();
485             } catch (Exception ex) {
486                 loge("mSatelliteAllowedReceiver: Got exception in releasing semaphore, ex=" + ex);
487             }
488         }
489     };
490 
491     private int mQueriedSatelliteVisibilityTime = -1;
492     private int mSatelliteNextVisibilityTime = 3600;
493     private int mQueriedSatelliteVisibilityTimeResultCode = SATELLITE_RESULT_SUCCESS;
494     private Semaphore mSatelliteVisibilityTimeSemaphore = new Semaphore(0);
495     private ResultReceiver mSatelliteVisibilityTimeReceiver = new ResultReceiver(null) {
496         @Override
497         protected void onReceiveResult(int resultCode, Bundle resultData) {
498             mQueriedSatelliteVisibilityTimeResultCode = resultCode;
499             logd("mSatelliteVisibilityTimeReceiver: resultCode=" + resultCode);
500             if (resultCode == SATELLITE_RESULT_SUCCESS) {
501                 if (resultData.containsKey(KEY_SATELLITE_NEXT_VISIBILITY)) {
502                     mQueriedSatelliteVisibilityTime = resultData.getInt(
503                             KEY_SATELLITE_NEXT_VISIBILITY);
504                 } else {
505                     loge("KEY_SATELLITE_NEXT_VISIBILITY does not exist.");
506                     mQueriedSatelliteVisibilityTime = -1;
507                 }
508             } else {
509                 mQueriedSatelliteVisibilityTime = -1;
510             }
511             try {
512                 mSatelliteVisibilityTimeSemaphore.release();
513             } catch (Exception ex) {
514                 loge("mSatelliteVisibilityTimeReceiver: Got exception in releasing semaphore, ex="
515                         + ex);
516             }
517         }
518     };
519 
520     private @NtnSignalStrength.NtnSignalStrengthLevel int mQueriedNtnSignalStrengthLevel =
521             NTN_SIGNAL_STRENGTH_NONE;
522     private int mQueriedNtnSignalStrengthResultCode = SATELLITE_RESULT_SUCCESS;
523     private Semaphore mRequestNtnSignalStrengthSemaphore = new Semaphore(0);
524     private ResultReceiver mRequestNtnSignalStrengthReceiver = new ResultReceiver(null) {
525         @Override
526         protected void onReceiveResult(int resultCode, Bundle resultData) {
527             mQueriedNtnSignalStrengthResultCode = resultCode;
528             logd("KEY_NTN_SIGNAL_STRENGTH: resultCode=" + resultCode);
529             if (resultCode == SATELLITE_RESULT_SUCCESS) {
530                 if (resultData.containsKey(KEY_NTN_SIGNAL_STRENGTH)) {
531                     NtnSignalStrength result = resultData.getParcelable(KEY_NTN_SIGNAL_STRENGTH);
532                     logd("result.getLevel()=" + result.getLevel());
533                     mQueriedNtnSignalStrengthLevel = result.getLevel();
534                 } else {
535                     loge("KEY_NTN_SIGNAL_STRENGTH does not exist.");
536                     mQueriedNtnSignalStrengthLevel = NTN_SIGNAL_STRENGTH_NONE;
537                 }
538             } else {
539                 mQueriedNtnSignalStrengthLevel = NTN_SIGNAL_STRENGTH_NONE;
540             }
541             try {
542                 mRequestNtnSignalStrengthSemaphore.release();
543             } catch (Exception ex) {
544                 loge("mRequestNtnSignalStrengthReceiver: Got exception in releasing semaphore, ex="
545                         + ex);
546             }
547         }
548     };
549 
550     private boolean mRequestIsEmergency = false;
551     private ResultReceiver mRequestIsEmergencyReceiver = new ResultReceiver(null) {
552         @Override
553         protected void onReceiveResult(int resultCode, Bundle resultData) {
554             logd("requestIsEmergencyReceiver: resultCode=" + resultCode);
555             if (resultCode == SATELLITE_RESULT_SUCCESS) {
556                 if (resultData.containsKey(KEY_EMERGENCY_MODE_ENABLED)) {
557                     mRequestIsEmergency = resultData.getBoolean(
558                             KEY_EMERGENCY_MODE_ENABLED);
559                 } else {
560                     loge("KEY_EMERGENCY_MODE_ENABLED does not exist.");
561 
562                 }
563             }
564         }
565     };
566 
567     private int mQueriedSystemSelectionChannelUpdatedResultCode = SATELLITE_RESULT_SUCCESS;
568     private Semaphore mSystemSelectionChannelUpdatedSemaphore = new Semaphore(0);
569     private ResultReceiver mSystemSelectionChannelUpdatedReceiver = new ResultReceiver(null) {
570         @Override
571         protected void onReceiveResult(int resultCode, Bundle resultData) {
572             mQueriedSystemSelectionChannelUpdatedResultCode = resultCode;
573             try {
574                 mSystemSelectionChannelUpdatedSemaphore.release();
575             } catch (Exception ex) {
576                 fail("mSystemSelectionChannelUpdatedReceiver: Got exception in releasing "
577                         + "semaphore, ex="
578                         + ex);
579             }
580         }
581     };
582 
583     @Rule
584     public final CheckFlagsRule mCheckFlagsRule =
585             DeviceFlagsValueProvider.createCheckFlagsRule();
586 
587     @Before
setUp()588     public void setUp() throws Exception {
589         super.setUp(getClass().getSimpleName());
590         MockitoAnnotations.initMocks(this);
591         logd(TAG + " Setup!");
592 
593         replaceInstance(SatelliteController.class, "sInstance", null,
594                 mMockSatelliteController);
595         replaceInstance(DatagramController.class, "sInstance", null,
596                 mMockDatagramController);
597         replaceInstance(SatelliteModemInterface.class, "sInstance", null,
598                 mMockSatelliteModemInterface);
599         replaceInstance(SatelliteSessionController.class, "sInstance", null,
600                 mMockSatelliteSessionController);
601         replaceInstance(PointingAppController.class, "sInstance", null,
602                 mMockPointingAppController);
603         replaceInstance(ControllerMetricsStats.class, "sInstance", null,
604                 mMockControllerMetricsStats);
605         replaceInstance(ProvisionMetricsStats.class, "sInstance", null,
606                 mMockProvisionMetricsStats);
607         replaceInstance(SessionMetricsStats.class, "sInstance", null,
608                 mMockSessionMetricsStats);
609         replaceInstance(SubscriptionManagerService.class, "sInstance", null,
610                 mMockSubscriptionManagerService);
611         replaceInstance(PhoneFactory.class, "sPhones", null, new Phone[]{mPhone, mPhone2});
612         replaceInstance(TelephonyConfigUpdateInstallReceiver.class, "sReceiverAdaptorInstance",
613                 null, mMockTelephonyConfigUpdateInstallReceiver);
614         replaceInstance(DemoSimulator.class, "sInstance", null, mMockDemoSimulator);
615 
616         doNothing().when(mMockSatelliteController).moveSatelliteToOffStateAndCleanUpResources(
617                 SATELLITE_RESULT_REQUEST_ABORTED);
618         mServiceState2 = mock(ServiceState.class);
619         when(mPhone.getServiceState()).thenReturn(mServiceState);
620         doReturn(SUB_ID).when(mPhone).getSubId();
621         when(mPhone.getPhoneId()).thenReturn(0);
622         when(mPhone.getSignalStrengthController()).thenReturn(mSignalStrengthController);
623         when(mPhone2.getServiceState()).thenReturn(mServiceState2);
624         doReturn(SUB_ID1).when(mPhone2).getSubId();
625         when(mPhone2.getPhoneId()).thenReturn(1);
626         when(mPhone2.getSignalStrengthController()).thenReturn(mSignalStrengthController);
627 
628         doReturn(Context.NETWORK_STATS_SERVICE).when(mContext).getSystemServiceName(
629                 NetworkStatsManager.class);
630         doReturn(mStatsManager).when(mContext).getSystemService(Context.NETWORK_STATS_SERVICE);
631         if (mContext.getSystemService(NetworkStatsManager.class) == null) {
632             // Test is using mockito-extended
633             doReturn(mStatsManager).when(mContext).getSystemService(NetworkStatsManager.class);
634         }
635 
636         mContextFixture.putStringArrayResource(
637                 R.array.config_satellite_providers,
638                 EMPTY_STRING_ARRAY);
639         mContextFixture.putIntResource(
640                 R.integer.config_wait_for_satellite_enabling_response_timeout_millis,
641                 TEST_WAIT_FOR_SATELLITE_ENABLING_RESPONSE_TIMEOUT_MILLIS);
642         mContextFixture.putIntResource(
643                 R.integer.config_satellite_wait_for_cellular_modem_off_timeout_millis,
644                 TEST_WAIT_FOR_CELLULAR_MODEM_OFF_TIMEOUT_MILLIS);
645         mContextFixture.putIntArrayResource(
646                 R.array.config_foldedDeviceStates,
647                 new int[0]);
648         mContextFixture.putBooleanResource(
649             R.bool.config_support_disable_satellite_while_enable_in_progress, true);
650         doReturn(ACTIVE_SUB_IDS).when(mMockSubscriptionManagerService).getActiveSubIdList(true);
651 
652         mCarrierConfigBundle = mContextFixture.getCarrierConfigBundle();
653         doReturn(mCarrierConfigBundle)
654                 .when(mCarrierConfigManager).getConfigForSubId(anyInt(), any());
655         doAnswer(invocation -> {
656             Executor executor = invocation.getArgument(0);
657             CarrierConfigManager.CarrierConfigChangeListener listener = invocation.getArgument(1);
658             mCarrierConfigChangedListenerList.add(new Pair<>(executor, listener));
659             return null;
660         }).when(mCarrierConfigManager).registerCarrierConfigChangeListener(
661                 any(Executor.class),
662                 any(CarrierConfigManager.CarrierConfigChangeListener.class));
663 
664         mSharedPreferences = new TestSharedPreferences();
665         when(mContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mSharedPreferences);
666         doReturn(mIsSatelliteServiceSupported)
667                 .when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
668         setUpResponseForRequestSatelliteCapabilities(
669                 mSatelliteCapabilities, SATELLITE_RESULT_SUCCESS);
670         setUpResponseForRequestIsSatelliteSupported(false,
671                 SATELLITE_RESULT_RADIO_NOT_AVAILABLE);
672         doNothing().when(mMockDatagramController).setDemoMode(anyBoolean());
673         doNothing().when(mMockSatelliteSessionController)
674                 .onSatelliteEnabledStateChanged(anyBoolean());
675         doNothing().when(mMockSatelliteSessionController).onSatelliteModemStateChanged(anyInt());
676         doNothing().when(mMockSatelliteSessionController).setDemoMode(anyBoolean());
677         doNothing().when(mMockSatelliteSessionController).cleanUpResource();
678         doNothing().when(mMockControllerMetricsStats).onSatelliteEnabled();
679         doNothing().when(mMockControllerMetricsStats).reportServiceEnablementSuccessCount();
680         doNothing().when(mMockControllerMetricsStats).reportServiceEnablementFailCount();
681         doReturn(mMockSessionMetricsStats)
682                 .when(mMockSessionMetricsStats).setInitializationResult(anyInt());
683         doReturn(mMockSessionMetricsStats)
684                 .when(mMockSessionMetricsStats).setSatelliteTechnology(anyInt());
685         doReturn(mMockSessionMetricsStats)
686                 .when(mMockSessionMetricsStats).setTerminationResult(anyInt());
687         doReturn(mMockSessionMetricsStats)
688                 .when(mMockSessionMetricsStats).setInitializationProcessingTime(anyLong());
689         doReturn(mMockSessionMetricsStats)
690                 .when(mMockSessionMetricsStats).setTerminationProcessingTime(anyLong());
691         doReturn(mMockSessionMetricsStats)
692                 .when(mMockSessionMetricsStats).setSessionDurationSec(anyInt());
693         doReturn(mMockSessionMetricsStats)
694                 .when(mMockSessionMetricsStats).setIsDemoMode(anyBoolean());
695         doReturn(mMockSessionMetricsStats)
696                 .when(mMockSessionMetricsStats).setCarrierId(anyInt());
697         doReturn(mMockSessionMetricsStats)
698                 .when(mMockSessionMetricsStats).setIsNtnOnlyCarrier(anyBoolean());
699         doNothing().when(mMockSessionMetricsStats).reportSessionMetrics();
700 
701         doReturn(mMockProvisionMetricsStats).when(mMockProvisionMetricsStats)
702                 .setResultCode(anyInt());
703         doReturn(mMockProvisionMetricsStats).when(mMockProvisionMetricsStats)
704                 .setIsProvisionRequest(anyBoolean());
705         doReturn(mMockProvisionMetricsStats).when(mMockProvisionMetricsStats)
706                 .setCarrierId(anyInt());
707         doReturn(mMockProvisionMetricsStats).when(mMockProvisionMetricsStats)
708                 .setIsNtnOnlyCarrier(anyBoolean());
709         doNothing().when(mMockProvisionMetricsStats).reportProvisionMetrics();
710         doNothing().when(mMockControllerMetricsStats).reportDeprovisionCount(anyInt());
711         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
712         doReturn(mSST).when(mPhone).getServiceStateTracker();
713         doReturn(mSST).when(mPhone2).getServiceStateTracker();
714         doReturn(mServiceState).when(mSST).getServiceState();
715         doReturn(Context.NOTIFICATION_SERVICE).when(mContext).getSystemServiceName(
716                 NotificationManager.class);
717         doReturn(mMockNotificationManager).when(mContext).getSystemService(
718                 Context.NOTIFICATION_SERVICE);
719         mSatelliteControllerUT =
720                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
721         verify(mMockSatelliteModemInterface).registerForPendingDatagrams(
722                 any(Handler.class),
723                 eq(27) /* EVENT_PENDING_DATAGRAMS */,
724                 eq(null));
725         verify(mMockSatelliteModemInterface).registerForSatelliteModemStateChanged(
726                 any(Handler.class),
727                 eq(28) /* EVENT_SATELLITE_MODEM_STATE_CHANGED */,
728                 eq(null));
729         doReturn(mMockConfigParser).when(mMockTelephonyConfigUpdateInstallReceiver)
730                 .getConfigParser(ConfigProviderAdaptor.DOMAIN_SATELLITE);
731         doReturn(mSubscriptionInfo).when(mMockSubscriptionManagerService).getSubscriptionInfo(
732                 anyInt());
733         doReturn("").when(mSubscriptionInfo).getIccId();
734         doReturn(TEST_ALL_SATELLITE_PLMN_SET).when(mMockSatelliteController).getAllPlmnSet();
735     }
736 
737     @After
tearDown()738     public void tearDown() throws Exception {
739         logd(TAG + " tearDown");
740         mSatelliteControllerUT = null;
741         super.tearDown();
742     }
743 
744     @Test
testShouldTurnOffCarrierSatelliteForEmergencyCall()745     public void testShouldTurnOffCarrierSatelliteForEmergencyCall() throws Exception {
746         DatagramController datagramController = mock(DatagramController.class);
747         replaceInstance(SatelliteController.class, "mDatagramController",
748                 mSatelliteControllerUT, datagramController);
749 
750         // Verify should turn off satellite
751         mCarrierConfigBundle.putBoolean(
752                 KEY_SATELLITE_ROAMING_TURN_OFF_SESSION_FOR_EMERGENCY_CALL_BOOL, true);
753         doReturn(false).when(datagramController).isEmergencyCommunicationEstablished();
754         invokeCarrierConfigChanged();
755         mSatelliteControllerUT.setSatellitePhone(1);
756         processAllMessages();
757 
758         assertTrue(mSatelliteControllerUT.shouldTurnOffCarrierSatelliteForEmergencyCall());
759 
760         // Verify should NOT turn off satellite
761         mCarrierConfigBundle.putBoolean(
762                 KEY_SATELLITE_ROAMING_TURN_OFF_SESSION_FOR_EMERGENCY_CALL_BOOL, false);
763         doReturn(true).when(datagramController).isEmergencyCommunicationEstablished();
764         invokeCarrierConfigChanged();
765         mSatelliteControllerUT.setSatellitePhone(1);
766         processAllMessages();
767 
768         assertFalse(mSatelliteControllerUT.shouldTurnOffCarrierSatelliteForEmergencyCall());
769     }
770 
771     @Test
testRequestTimeForNextSatelliteVisibility()772     public void testRequestTimeForNextSatelliteVisibility() {
773         mSatelliteVisibilityTimeSemaphore.drainPermits();
774         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
775         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
776         mSatelliteControllerUT.requestTimeForNextSatelliteVisibility(
777                 mSatelliteVisibilityTimeReceiver);
778         processAllMessages();
779         assertTrue(waitForRequestTimeForNextSatelliteVisibilityResult(1));
780         assertEquals(SATELLITE_RESULT_NOT_SUPPORTED, mQueriedSatelliteVisibilityTimeResultCode);
781 
782         resetSatelliteControllerUT();
783         mSatelliteControllerUT.requestTimeForNextSatelliteVisibility(
784                 mSatelliteVisibilityTimeReceiver);
785         processAllMessages();
786         assertTrue(waitForRequestTimeForNextSatelliteVisibilityResult(1));
787         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
788                 mQueriedSatelliteVisibilityTimeResultCode);
789 
790         resetSatelliteControllerUT();
791         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
792         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
793         setUpResponseForRequestTimeForNextSatelliteVisibility(mSatelliteNextVisibilityTime,
794                 SATELLITE_RESULT_SUCCESS);
795         mSatelliteControllerUT.requestTimeForNextSatelliteVisibility(
796                 mSatelliteVisibilityTimeReceiver);
797         processAllMessages();
798         assertTrue(waitForRequestTimeForNextSatelliteVisibilityResult(1));
799         assertEquals(SATELLITE_RESULT_SERVICE_NOT_PROVISIONED,
800                 mQueriedSatelliteVisibilityTimeResultCode);
801 
802         resetSatelliteControllerUT();
803         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
804         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
805         setUpResponseForRequestIsSatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
806         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
807         setUpResponseForRequestTimeForNextSatelliteVisibility(mSatelliteNextVisibilityTime,
808                 SATELLITE_RESULT_SUCCESS);
809         mSatelliteControllerUT.requestTimeForNextSatelliteVisibility(
810                 mSatelliteVisibilityTimeReceiver);
811         processAllMessages();
812         assertTrue(waitForRequestTimeForNextSatelliteVisibilityResult(1));
813         assertEquals(SATELLITE_RESULT_SERVICE_NOT_PROVISIONED,
814                 mQueriedSatelliteVisibilityTimeResultCode);
815 
816         resetSatelliteControllerUT();
817         provisionSatelliteService();
818         setUpResponseForRequestTimeForNextSatelliteVisibility(mSatelliteNextVisibilityTime,
819                 SATELLITE_RESULT_SUCCESS);
820         mSatelliteControllerUT.requestTimeForNextSatelliteVisibility(
821                 mSatelliteVisibilityTimeReceiver);
822         processAllMessages();
823         assertTrue(waitForRequestTimeForNextSatelliteVisibilityResult(1));
824         assertEquals(SATELLITE_RESULT_SUCCESS, mQueriedSatelliteVisibilityTimeResultCode);
825         assertEquals(mSatelliteNextVisibilityTime, mQueriedSatelliteVisibilityTime);
826 
827         resetSatelliteControllerUT();
828         provisionSatelliteService();
829         setUpNullResponseForRequestTimeForNextSatelliteVisibility(
830                 SATELLITE_RESULT_SUCCESS);
831         mSatelliteControllerUT.requestTimeForNextSatelliteVisibility(
832                 mSatelliteVisibilityTimeReceiver);
833         processAllMessages();
834         assertTrue(waitForRequestTimeForNextSatelliteVisibilityResult(1));
835         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
836                 mQueriedSatelliteVisibilityTimeResultCode);
837 
838         resetSatelliteControllerUT();
839         provisionSatelliteService();
840         setUpNullResponseForRequestTimeForNextSatelliteVisibility(
841                 SATELLITE_RESULT_INVALID_MODEM_STATE);
842         mSatelliteControllerUT.requestTimeForNextSatelliteVisibility(
843                 mSatelliteVisibilityTimeReceiver);
844         processAllMessages();
845         assertTrue(waitForRequestTimeForNextSatelliteVisibilityResult(1));
846         assertEquals(SATELLITE_RESULT_INVALID_MODEM_STATE,
847                 mQueriedSatelliteVisibilityTimeResultCode);
848     }
849 
850     @Test
testRadioStateChanged()851     public void testRadioStateChanged() {
852         mIsSatelliteEnabledSemaphore.drainPermits();
853 
854         when(mMockSatelliteModemInterface.isSatelliteServiceConnected()).thenReturn(false);
855         setRadioPower(false);
856         processAllMessages();
857         verify(mMockSatelliteModemInterface, never())
858                 .requestIsSatelliteSupported(any(Message.class));
859 
860         setRadioPower(true);
861         processAllMessages();
862         verify(mMockSatelliteModemInterface, never())
863                 .requestIsSatelliteSupported(any(Message.class));
864 
865         when(mMockSatelliteModemInterface.isSatelliteServiceConnected()).thenReturn(true);
866         setRadioPower(false);
867         processAllMessages();
868         verify(mMockSatelliteModemInterface, times(1))
869                 .requestIsSatelliteSupported(any(Message.class));
870 
871         setRadioPower(true);
872         processAllMessages();
873         verify(mMockSatelliteModemInterface, times(2))
874                 .requestIsSatelliteSupported(any(Message.class));
875 
876         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
877         setRadioPower(false);
878         processAllMessages();
879         verify(mMockSatelliteModemInterface, times(3))
880                 .requestIsSatelliteSupported(any(Message.class));
881 
882         setRadioPower(true);
883         processAllMessages();
884         verify(mMockSatelliteModemInterface, times(4))
885                 .requestIsSatelliteSupported(any(Message.class));
886 
887         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
888         setRadioPower(false);
889         processAllMessages();
890         verify(mMockSatelliteModemInterface, times(5))
891                 .requestIsSatelliteSupported(any(Message.class));
892 
893         setRadioPower(true);
894         processAllMessages();
895         verify(mMockSatelliteModemInterface, times(5))
896                 .requestIsSatelliteSupported(any(Message.class));
897         assertTrue(mSatelliteControllerUT.isRadioOn());
898         assertFalse(mSatelliteControllerUT.isRadioOffRequested());
899         assertFalse(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
900 
901         // Radio is off during TN -> NTN image switch, SatelliteController should not set radio
902         // state to OFF
903         setRadioPower(false);
904         processAllMessages();
905         assertTrue(mSatelliteControllerUT.isRadioOn());
906         assertFalse(mSatelliteControllerUT.isRadioOffRequested());
907         assertFalse(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
908 
909         // Turn on radio
910         setRadioPower(true);
911         processAllMessages();
912         assertTrue(mSatelliteControllerUT.isRadioOn());
913         assertFalse(mSatelliteControllerUT.isRadioOffRequested());
914         assertFalse(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
915 
916         // APM is triggered
917         mSatelliteControllerUT.onSetCellularRadioPowerStateRequested(false);
918         processAllMessages();
919         assertTrue(mSatelliteControllerUT.isRadioOn());
920         assertTrue(mSatelliteControllerUT.isRadioOffRequested());
921         assertTrue(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
922 
923         // SatelliteController should set the radio state to OFF
924         setRadioPower(false);
925         processAllMessages();
926         assertFalse(mSatelliteControllerUT.isRadioOn());
927         assertFalse(mSatelliteControllerUT.isRadioOffRequested());
928         assertFalse(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
929 
930         // Turn on radio
931         setRadioPower(true);
932         processAllMessages();
933         assertTrue(mSatelliteControllerUT.isRadioOn());
934         assertFalse(mSatelliteControllerUT.isRadioOffRequested());
935         assertFalse(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
936 
937         // APM is triggered
938         mSatelliteControllerUT.onSetCellularRadioPowerStateRequested(false);
939         processAllMessages();
940         assertTrue(mSatelliteControllerUT.isRadioOn());
941         assertTrue(mSatelliteControllerUT.isRadioOffRequested());
942         assertTrue(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
943 
944         // Modem fails to power off radio. APM is disabled
945         mSatelliteControllerUT.onSetCellularRadioPowerStateRequested(true);
946         processAllMessages();
947         assertTrue(mSatelliteControllerUT.isRadioOn());
948         assertFalse(mSatelliteControllerUT.isRadioOffRequested());
949         assertFalse(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
950 
951         // APM is triggered
952         mSatelliteControllerUT.onSetCellularRadioPowerStateRequested(false);
953         processAllMessages();
954         assertTrue(mSatelliteControllerUT.isRadioOn());
955         assertTrue(mSatelliteControllerUT.isRadioOffRequested());
956         assertTrue(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
957 
958         // The timer WaitForCellularModemOff time out
959         moveTimeForward(TEST_WAIT_FOR_CELLULAR_MODEM_OFF_TIMEOUT_MILLIS);
960         processAllMessages();
961         assertTrue(mSatelliteControllerUT.isRadioOn());
962         assertFalse(mSatelliteControllerUT.isRadioOffRequested());
963         assertFalse(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
964 
965         // APM is triggered
966         mSatelliteControllerUT.onSetCellularRadioPowerStateRequested(false);
967         processAllMessages();
968         assertTrue(mSatelliteControllerUT.isRadioOn());
969         assertTrue(mSatelliteControllerUT.isRadioOffRequested());
970         assertTrue(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
971 
972         // Modem failed to power off the radio
973         mSatelliteControllerUT.onPowerOffCellularRadioFailed();
974         processAllMessages();
975         assertTrue(mSatelliteControllerUT.isRadioOn());
976         assertFalse(mSatelliteControllerUT.isRadioOffRequested());
977         assertFalse(mSatelliteControllerUT.isWaitForCellularModemOffTimerStarted());
978     }
979 
980     @Test
testRadioPowerOff()981     public void testRadioPowerOff() {
982         NetworkRegistrationInfo satelliteNri = new NetworkRegistrationInfo.Builder()
983                 .setIsNonTerrestrialNetwork(true)
984                 .setAvailableServices(List.of(NetworkRegistrationInfo.SERVICE_TYPE_DATA))
985                 .build();
986         mCarrierConfigBundle.putInt(KEY_SATELLITE_CONNECTION_HYSTERESIS_SEC_INT, 1 * 60);
987         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
988         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
989                 : mCarrierConfigChangedListenerList) {
990             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
991                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
992             );
993         }
994         when(mServiceState.getNetworkRegistrationInfoList()).thenReturn(List.of(satelliteNri));
995         when(mServiceState.isUsingNonTerrestrialNetwork()).thenReturn(true);
996         sendServiceStateChangedEvent();
997         processAllMessages();
998         assertTrue(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone));
999         assertEquals(List.of(SERVICE_TYPE_DATA),
1000                 mSatelliteControllerUT.getCapabilitiesForCarrierRoamingSatelliteMode(mPhone));
1001 
1002         when(mServiceState.isUsingNonTerrestrialNetwork()).thenReturn(false);
1003         setRadioPower(false);
1004         processAllMessages();
1005         assertFalse(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone));
1006         assertEquals(new ArrayList<>(),
1007                 mSatelliteControllerUT.getCapabilitiesForCarrierRoamingSatelliteMode(mPhone));
1008     }
1009 
1010     @Test
testRequestSatelliteEnabled()1011     public void testRequestSatelliteEnabled() {
1012         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
1013         when(mFeatureFlags.satelliteStateChangeListener()).thenReturn(true);
1014         mIsSatelliteEnabledSemaphore.drainPermits();
1015         mSatelliteControllerUT.handleSatelliteAccessAllowedStateChanged(true);
1016 
1017         // Fail to enable satellite when SatelliteController is not fully loaded yet.
1018         mIIntegerConsumerResults.clear();
1019         mIIntegerConsumerSemaphore.drainPermits();
1020         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1021         processAllMessages();
1022         assertTrue(waitForIIntegerConsumerResult(1));
1023         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
1024                 (long) mIIntegerConsumerResults.get(0));
1025 
1026         // Fail to enable satellite when the device does not support satellite.
1027         mIIntegerConsumerResults.clear();
1028         mIIntegerConsumerSemaphore.drainPermits();
1029         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1030         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1031         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1032         processAllMessages();
1033         assertTrue(waitForIIntegerConsumerResult(1));
1034         assertEquals(SATELLITE_RESULT_NOT_SUPPORTED, (long) mIIntegerConsumerResults.get(0));
1035 
1036         // Fail to enable satellite when the device is not provisioned yet.
1037         mIIntegerConsumerResults.clear();
1038         mIIntegerConsumerSemaphore.drainPermits();
1039         resetSatelliteControllerUT();
1040         verify(mMockSatelliteSessionController, times(1)).onSatelliteEnabledStateChanged(eq(false));
1041         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1042         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1043         setUpResponseForRequestIsSatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1044         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1045         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1046         processAllMessages();
1047         assertTrue(waitForIIntegerConsumerResult(1));
1048         assertEquals(SATELLITE_RESULT_SERVICE_NOT_PROVISIONED,
1049                 (long) mIIntegerConsumerResults.get(0));
1050 
1051         setProvisionedState(true);
1052         processAllMessages();
1053         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
1054 
1055         // Fail to enable satellite when the emergency call is in progress
1056         mIIntegerConsumerResults.clear();
1057         mIIntegerConsumerSemaphore.drainPermits();
1058         mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled = false;
1059         mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled = false;
1060         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
1061         doReturn(true).when(mTelecomManager).isInEmergencyCall();
1062         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1063         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
1064         processAllMessages();
1065         assertTrue(waitForIIntegerConsumerResult(1));
1066         assertEquals(SATELLITE_RESULT_EMERGENCY_CALL_IN_PROGRESS,
1067                 (long) mIIntegerConsumerResults.get(0));
1068         doReturn(false).when(mTelecomManager).isInEmergencyCall();
1069 
1070         // Successfully enable satellite
1071         reset(mTelephonyRegistryManager);
1072         mIIntegerConsumerResults.clear();
1073         mIIntegerConsumerSemaphore.drainPermits();
1074         mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled = false;
1075         mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled = false;
1076         setUpResponseForRequestSatelliteEnabled(true, false, true, SATELLITE_RESULT_SUCCESS);
1077         mSatelliteControllerUT.requestSatelliteEnabled(true, false, true, mIIntegerConsumer);
1078         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
1079         processAllMessages();
1080         assertTrue(waitForIIntegerConsumerResult(1));
1081         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1082         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
1083         verify(mMockSatelliteSessionController, times(1)).onEmergencyModeChanged(eq(true));
1084         assertTrue(mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled);
1085         assertTrue(mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled);
1086         assertEquals(
1087                 SATELLITE_MODE_ENABLED_TRUE, mSatelliteControllerUT.satelliteModeSettingValue);
1088         verify(mMockSatelliteSessionController, times(1)).onSatelliteEnabledStateChanged(eq(true));
1089         verify(mMockSatelliteSessionController, times(2)).setDemoMode(eq(false));
1090         verify(mMockDatagramController, times(2)).setDemoMode(eq(false));
1091         verify(mMockControllerMetricsStats, times(1)).onSatelliteEnabled();
1092         verify(mMockControllerMetricsStats, times(1)).reportServiceEnablementSuccessCount();
1093         verify(mTelephonyRegistryManager).notifySatelliteStateChanged(eq(true));
1094 
1095         // Successfully disable satellite when radio is turned off.
1096         reset(mTelephonyRegistryManager);
1097         clearInvocations(mMockSatelliteSessionController);
1098         clearInvocations(mMockDatagramController);
1099         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
1100         mSatelliteControllerUT.isSatelliteBeingDisabled = true;
1101         mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled = false;
1102         mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled = false;
1103         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
1104         setRadioPower(false);
1105         mSatelliteControllerUT.onSetCellularRadioPowerStateRequested(false);
1106         processAllMessages();
1107         sendSatelliteModemStateChangedEvent(SATELLITE_MODEM_STATE_OFF, null);
1108         processAllMessages();
1109         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1110         verify(mMockSatelliteSessionController, times(1)).onEmergencyModeChanged(eq(false));
1111         assertTrue(mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled);
1112         assertTrue(mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled);
1113         assertEquals(
1114                 SATELLITE_MODE_ENABLED_FALSE, mSatelliteControllerUT.satelliteModeSettingValue);
1115         verify(mMockSatelliteSessionController, times(2)).onSatelliteEnabledStateChanged(eq(false));
1116         verify(mMockSatelliteSessionController, times(2)).setDemoMode(eq(false));
1117         verify(mMockDatagramController, times(2)).setDemoMode(eq(false));
1118         verify(mMockControllerMetricsStats, times(1)).onSatelliteDisabled();
1119         mSatelliteControllerUT.isSatelliteBeingDisabled = false;
1120         verify(mTelephonyRegistryManager, atLeastOnce()).notifySatelliteStateChanged(eq(false));
1121 
1122         // Fail to enable satellite when radio is off.
1123         mIIntegerConsumerResults.clear();
1124         mIIntegerConsumerSemaphore.drainPermits();
1125         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
1126         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1127         processAllMessages();
1128         assertTrue(waitForIIntegerConsumerResult(1));
1129         // Radio is not on, can not enable satellite
1130         assertEquals(SATELLITE_RESULT_INVALID_MODEM_STATE, (long) mIIntegerConsumerResults.get(0));
1131 
1132         setRadioPower(true);
1133         processAllMessages();
1134         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1135 
1136         // Fail to enable satellite with an error response from modem when radio is on.
1137         mIIntegerConsumerResults.clear();
1138         mIIntegerConsumerSemaphore.drainPermits();
1139         clearInvocations(mMockPointingAppController);
1140         mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled = false;
1141         mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled = false;
1142         setUpResponseForRequestSatelliteEnabled(true, false, false,
1143                 SATELLITE_RESULT_INVALID_MODEM_STATE);
1144         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1145         processAllMessages();
1146         assertTrue(waitForIIntegerConsumerResult(1));
1147         assertEquals(SATELLITE_RESULT_INVALID_MODEM_STATE, (long) mIIntegerConsumerResults.get(0));
1148         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1149         verify(mMockPointingAppController, never()).startPointingUI(anyBoolean(), anyBoolean(),
1150                 anyBoolean());
1151         assertFalse(mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled);
1152         assertFalse(mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled);
1153         verify(mMockControllerMetricsStats, times(1)).reportServiceEnablementFailCount();
1154 
1155         // Successfully enable satellite when radio is on.
1156         reset(mTelephonyRegistryManager);
1157         mIIntegerConsumerResults.clear();
1158         mIIntegerConsumerSemaphore.drainPermits();
1159         mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled = false;
1160         mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled = false;
1161         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
1162         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1163         processAllMessages();
1164         assertTrue(waitForIIntegerConsumerResult(1));
1165         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1166         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
1167         assertTrue(mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled);
1168         assertTrue(mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled);
1169         assertEquals(SATELLITE_MODE_ENABLED_TRUE, mSatelliteControllerUT.satelliteModeSettingValue);
1170         verify(mMockSatelliteSessionController, times(1)).onSatelliteEnabledStateChanged(eq(true));
1171         verify(mMockSatelliteSessionController, times(3)).setDemoMode(eq(false));
1172         verify(mMockDatagramController, times(3)).setDemoMode(eq(false));
1173         verify(mMockControllerMetricsStats, times(2)).onSatelliteEnabled();
1174         verify(mMockControllerMetricsStats, times(2)).reportServiceEnablementSuccessCount();
1175         verify(mTelephonyRegistryManager).notifySatelliteStateChanged(eq(true));
1176 
1177         // Successfully enable satellite when it is already enabled.
1178         mIIntegerConsumerResults.clear();
1179         mIIntegerConsumerSemaphore.drainPermits();
1180         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1181         processAllMessages();
1182         assertTrue(waitForIIntegerConsumerResult(1));
1183         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1184         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
1185 
1186         // Fail to enable satellite with a different demo mode when it is already enabled.
1187         mIIntegerConsumerResults.clear();
1188         mIIntegerConsumerSemaphore.drainPermits();
1189         mSatelliteControllerUT.requestSatelliteEnabled(true, true, false, mIIntegerConsumer);
1190         processAllMessages();
1191         assertTrue(waitForIIntegerConsumerResult(1));
1192         assertEquals(SATELLITE_RESULT_INVALID_ARGUMENTS, (long) mIIntegerConsumerResults.get(0));
1193         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
1194 
1195         // Successfully disable satellite.
1196         reset(mTelephonyRegistryManager);
1197         mIIntegerConsumerResults.clear();
1198         mIIntegerConsumerSemaphore.drainPermits();
1199         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
1200         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
1201         processAllMessages();
1202         assertTrue(waitForIIntegerConsumerResult(1));
1203         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1204         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1205         verify(mTelephonyRegistryManager, atLeastOnce()).notifySatelliteStateChanged(eq(false));
1206 
1207         // Disable satellite when satellite is already disabled.
1208         mIIntegerConsumerResults.clear();
1209         mIIntegerConsumerSemaphore.drainPermits();
1210         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
1211         processAllMessages();
1212         assertTrue(waitForIIntegerConsumerResult(1));
1213         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1214         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1215 
1216         // Disable satellite with a different demo mode when satellite is already disabled.
1217         mIIntegerConsumerResults.clear();
1218         mIIntegerConsumerSemaphore.drainPermits();
1219         mSatelliteControllerUT.requestSatelliteEnabled(false, true, false, mIIntegerConsumer);
1220         processAllMessages();
1221         assertTrue(waitForIIntegerConsumerResult(1));
1222         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1223         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1224 
1225         // Send a second request while the first request in progress
1226         mIIntegerConsumerResults.clear();
1227         mIIntegerConsumerSemaphore.drainPermits();
1228         setUpNoResponseForRequestSatelliteEnabled(true, false, false);
1229         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1230         processAllMessages();
1231         assertFalse(waitForIIntegerConsumerResult(1));
1232         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1233         processAllMessages();
1234         assertTrue(waitForIIntegerConsumerResult(1));
1235         assertEquals(SATELLITE_RESULT_REQUEST_IN_PROGRESS, (long) mIIntegerConsumerResults.get(0));
1236 
1237         mIIntegerConsumerResults.clear();
1238         mIIntegerConsumerSemaphore.drainPermits();
1239         resetSatelliteControllerUT();
1240         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1241         setProvisionedState(false);
1242         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1243         setProvisionedState(true);
1244         processAllMessages();
1245         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
1246         // The enable request should be aborted when satellite modem move to OFF state.
1247         assertTrue(waitForIIntegerConsumerResult(1));
1248         assertEquals(SATELLITE_RESULT_REQUEST_ABORTED, (long) mIIntegerConsumerResults.get(0));
1249 
1250         // Successfully enable satellite
1251         mIIntegerConsumerResults.clear();
1252         mIIntegerConsumerSemaphore.drainPermits();
1253         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
1254         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1255         processAllMessages();
1256         assertTrue(waitForIIntegerConsumerResult(1));
1257         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1258         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
1259 
1260         // Move to satellite-disabling in progress.
1261         mIIntegerConsumerResults.clear();
1262         mIIntegerConsumerSemaphore.drainPermits();
1263         setUpNoResponseForRequestSatelliteEnabled(false, false, false);
1264         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
1265         processAllMessages();
1266         assertFalse(waitForIIntegerConsumerResult(1));
1267 
1268         // Disable is in progress. Thus, a new request to enable satellite will be rejected.
1269         mIIntegerConsumerResults.clear();
1270         mIIntegerConsumerSemaphore.drainPermits();
1271         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
1272         mSatelliteControllerUT.isSatelliteBeingDisabled = true;
1273         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1274         processAllMessages();
1275         assertTrue(waitForIIntegerConsumerResult(1));
1276         assertEquals(SATELLITE_RESULT_DISABLE_IN_PROGRESS, (long) mIIntegerConsumerResults.get(0));
1277 
1278         mIIntegerConsumerResults.clear();
1279         mIIntegerConsumerSemaphore.drainPermits();
1280         resetSatelliteControllerUTToOffAndProvisionedState();
1281         mSatelliteControllerUT.isSatelliteBeingDisabled = false;
1282 
1283         /**
1284          * Make areAllRadiosDisabled return false and move mWaitingForRadioDisabled to true, which
1285          * will lead to no response for requestSatelliteEnabled.
1286          */
1287         mSatelliteControllerUT.allRadiosDisabled = false;
1288         mIIntegerConsumerResults.clear();
1289         mIIntegerConsumerSemaphore.drainPermits();
1290         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
1291         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1292         processAllMessages();
1293         assertFalse(waitForIIntegerConsumerResult(1));
1294 
1295         mIIntegerConsumerResults.clear();
1296         mIIntegerConsumerSemaphore.drainPermits();
1297         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
1298         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
1299         processAllMessages();
1300         // We should receive 2 callbacks for the above 2 requests.
1301         assertTrue(waitForIIntegerConsumerResult(2));
1302         // Successful result for disable request
1303         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1304         // The enable request should be aborted after getting the successful confirmation of the
1305         // disable request.
1306         assertEquals(SATELLITE_RESULT_REQUEST_ABORTED, (long) mIIntegerConsumerResults.get(1));
1307 
1308         resetSatelliteControllerUTToOffAndProvisionedState();
1309 
1310         // Repeat the same test as above but with error response from modem for the second request
1311         mSatelliteControllerUT.allRadiosDisabled = false;
1312         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
1313         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1314         processAllMessages();
1315         // No response for the enable request because all radios are not disabled yet
1316         assertFalse(waitForIIntegerConsumerResult(1));
1317 
1318         mIIntegerConsumerResults.clear();
1319         mIIntegerConsumerSemaphore.drainPermits();
1320         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_NO_RESOURCES);
1321         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
1322         processAllMessages();
1323         // We should receive result for the disable request.
1324         assertTrue(waitForIIntegerConsumerResult(1));
1325         assertEquals(SATELLITE_RESULT_NO_RESOURCES, (long) mIIntegerConsumerResults.get(0));
1326         mSatelliteControllerUT.allRadiosDisabled = true;
1327 
1328         resetSatelliteControllerUTToOnAndProvisionedState();
1329         mSatelliteControllerUT.onSetCellularRadioPowerStateRequested(false);
1330         processAllMessages();
1331         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
1332 
1333         // Successfully disable satellite.
1334         mIIntegerConsumerResults.clear();
1335         mIIntegerConsumerSemaphore.drainPermits();
1336         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
1337         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
1338         processAllMessages();
1339         assertTrue(waitForIIntegerConsumerResult(1));
1340         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1341         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1342 
1343         // Fail to enable satellite when radio is being powered off.
1344         mIIntegerConsumerResults.clear();
1345         mIIntegerConsumerSemaphore.drainPermits();
1346         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
1347         mSatelliteControllerUT.onSetCellularRadioPowerStateRequested(false);
1348         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1349         processAllMessages();
1350         assertTrue(waitForIIntegerConsumerResult(1));
1351         // Radio is being powered off, can not enable satellite
1352         assertEquals(SATELLITE_RESULT_INVALID_MODEM_STATE, (long) mIIntegerConsumerResults.get(0));
1353 
1354         // Modem failed to power off
1355         mSatelliteControllerUT.onPowerOffCellularRadioFailed();
1356 
1357         // Successfully enable satellite when radio is on.
1358         mIIntegerConsumerResults.clear();
1359         mIIntegerConsumerSemaphore.drainPermits();
1360         mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled = false;
1361         mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled = false;
1362         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
1363         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1364         processAllMessages();
1365         assertTrue(waitForIIntegerConsumerResult(1));
1366         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1367         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
1368 
1369         // Clean up all previous resources
1370         processAllFutureMessages();
1371         mIIntegerConsumerSemaphore.drainPermits();
1372 
1373         // Successfully disable satellite.
1374         mIIntegerConsumerResults.clear();
1375         mIIntegerConsumerSemaphore.drainPermits();
1376         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
1377         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
1378         processAllMessages();
1379         assertTrue(waitForIIntegerConsumerResult(1));
1380         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1381         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1382 
1383         // Move to satellite-enabling in progress.
1384         setUpNoResponseForRequestSatelliteEnabled(true, false, false);
1385         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
1386         processAllMessages();
1387         assertFalse(waitForIIntegerConsumerResult(1));
1388 
1389         // Successfully disable satellite.
1390         mIIntegerConsumerResults.clear();
1391         mIIntegerConsumerSemaphore.drainPermits();
1392         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
1393         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
1394         processAllMessages();
1395         assertTrue(waitForIIntegerConsumerResult(2));
1396         // Should get success result for the disable request
1397         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1398         // The enable request should be aborted
1399         assertEquals(SATELLITE_RESULT_REQUEST_ABORTED, (long) mIIntegerConsumerResults.get(1));
1400         // All timers waiting for enablement response should be stopped
1401         assertFalse(mSatelliteControllerUT.isAnyWaitForSatelliteEnablingResponseTimerStarted());
1402         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1403     }
1404 
1405     @Test
testGetRequestIsEmergency()1406     public void testGetRequestIsEmergency() {
1407         mIsSatelliteEnabledSemaphore.drainPermits();
1408         doReturn(true).when(mFeatureFlags).carrierRoamingNbIotNtn();
1409 
1410         // Successfully enable satellite
1411         mIIntegerConsumerResults.clear();
1412         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1413         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1414 
1415         // Set provisioned state
1416         setProvisionedState(true);
1417         processAllMessages();
1418         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
1419 
1420         mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled = false;
1421         mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled = false;
1422         // Set response for enabling request
1423         setUpResponseForRequestSatelliteEnabled(true, false, true/*emergency*/,
1424                 SATELLITE_RESULT_SUCCESS);
1425         // Request satellite enabling for emergency
1426         mSatelliteControllerUT.requestSatelliteEnabled(true, false, true /*isEmergency*/,
1427                 mIIntegerConsumer);
1428         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
1429         processAllMessages();
1430 
1431         assertTrue(waitForIIntegerConsumerResult(1));
1432         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1433         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
1434 
1435         // Verify satellite enabled for emergency
1436         assertTrue(mSatelliteControllerUT.getRequestIsEmergency());
1437         mSatelliteControllerUT.requestIsEmergencyModeEnabled(mRequestIsEmergencyReceiver);
1438         assertTrue(mRequestIsEmergency);
1439     }
1440 
1441     @Test
testRequestSatelliteCapabilities()1442     public void testRequestSatelliteCapabilities() {
1443         mSatelliteCapabilitiesSemaphore.drainPermits();
1444         mSatelliteControllerUT.requestSatelliteCapabilities(mSatelliteCapabilitiesReceiver);
1445         processAllMessages();
1446         assertTrue(waitForRequestSatelliteCapabilitiesResult(1));
1447         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
1448                 mQueriedSatelliteCapabilitiesResultCode);
1449 
1450         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1451         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1452         mSatelliteControllerUT.requestSatelliteCapabilities(mSatelliteCapabilitiesReceiver);
1453         processAllMessages();
1454         assertTrue(waitForRequestSatelliteCapabilitiesResult(1));
1455         assertEquals(SATELLITE_RESULT_NOT_SUPPORTED, mQueriedSatelliteCapabilitiesResultCode);
1456 
1457         resetSatelliteControllerUT();
1458         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1459         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1460         setUpResponseForRequestSatelliteCapabilities(mSatelliteCapabilities,
1461                 SATELLITE_RESULT_SUCCESS);
1462         mSatelliteControllerUT.requestSatelliteCapabilities(mSatelliteCapabilitiesReceiver);
1463         processAllMessages();
1464         assertTrue(waitForRequestSatelliteCapabilitiesResult(1));
1465         assertEquals(SATELLITE_RESULT_SUCCESS, mQueriedSatelliteCapabilitiesResultCode);
1466         assertEquals(mSatelliteCapabilities, mQueriedSatelliteCapabilities);
1467         assertTrue(
1468                 mQueriedSatelliteCapabilities.getSupportedRadioTechnologies().contains(
1469                         mSatelliteControllerUT.getSupportedNtnRadioTechnology()));
1470 
1471         resetSatelliteControllerUT();
1472         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1473         setUpNullResponseForRequestSatelliteCapabilities(SATELLITE_RESULT_SUCCESS);
1474         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1475         mSatelliteControllerUT.requestSatelliteCapabilities(mSatelliteCapabilitiesReceiver);
1476         processAllMessages();
1477         assertTrue(waitForRequestSatelliteCapabilitiesResult(1));
1478         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
1479                 mQueriedSatelliteCapabilitiesResultCode);
1480 
1481         resetSatelliteControllerUT();
1482         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1483         setUpNullResponseForRequestSatelliteCapabilities(SATELLITE_RESULT_INVALID_MODEM_STATE);
1484         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1485         mSatelliteControllerUT.requestSatelliteCapabilities(mSatelliteCapabilitiesReceiver);
1486         processAllMessages();
1487         assertTrue(waitForRequestSatelliteCapabilitiesResult(1));
1488         assertEquals(SATELLITE_RESULT_INVALID_MODEM_STATE, mQueriedSatelliteCapabilitiesResultCode);
1489     }
1490 
1491     @Test
testStartSatelliteTransmissionUpdates()1492     public void testStartSatelliteTransmissionUpdates() {
1493         mIIntegerConsumerSemaphore.drainPermits();
1494         mIIntegerConsumerResults.clear();
1495         mSatelliteControllerUT.startSatelliteTransmissionUpdates(mIIntegerConsumer,
1496                 mStartTransmissionUpdateCallback);
1497         processAllMessages();
1498         assertTrue(waitForIIntegerConsumerResult(1));
1499         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
1500                 (long) mIIntegerConsumerResults.get(0));
1501 
1502         mIIntegerConsumerResults.clear();
1503         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1504         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1505         mSatelliteControllerUT.startSatelliteTransmissionUpdates(mIIntegerConsumer,
1506                 mStartTransmissionUpdateCallback);
1507         processAllMessages();
1508         assertTrue(waitForIIntegerConsumerResult(1));
1509         assertEquals(SATELLITE_RESULT_NOT_SUPPORTED, (long) mIIntegerConsumerResults.get(0));
1510 
1511         resetSatelliteControllerUT();
1512         mIIntegerConsumerResults.clear();
1513         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1514         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1515         mSatelliteControllerUT.startSatelliteTransmissionUpdates(mIIntegerConsumer,
1516                 mStartTransmissionUpdateCallback);
1517         processAllMessages();
1518         assertTrue(waitForIIntegerConsumerResult(1));
1519         assertEquals(SATELLITE_RESULT_SERVICE_NOT_PROVISIONED,
1520                 (long) mIIntegerConsumerResults.get(0));
1521 
1522         resetSatelliteControllerUT();
1523         mIIntegerConsumerResults.clear();
1524         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1525         setUpResponseForRequestIsSatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1526         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1527         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1528         setUpResponseForStartSatelliteTransmissionUpdates(SATELLITE_RESULT_SUCCESS);
1529         mSatelliteControllerUT.startSatelliteTransmissionUpdates(mIIntegerConsumer,
1530                 mStartTransmissionUpdateCallback);
1531         processAllMessages();
1532         assertTrue(waitForIIntegerConsumerResult(1));
1533         assertEquals(SATELLITE_RESULT_SERVICE_NOT_PROVISIONED,
1534                 (long) mIIntegerConsumerResults.get(0));
1535 
1536         resetSatelliteControllerUT();
1537         provisionSatelliteService();
1538         mIIntegerConsumerResults.clear();
1539         setUpResponseForStartSatelliteTransmissionUpdates(SATELLITE_RESULT_SUCCESS);
1540         mSatelliteControllerUT.startSatelliteTransmissionUpdates(mIIntegerConsumer,
1541                 mStartTransmissionUpdateCallback);
1542         verify(mMockPointingAppController).registerForSatelliteTransmissionUpdates(anyInt(),
1543                 eq(mStartTransmissionUpdateCallback));
1544         processAllMessages();
1545         assertTrue(waitForIIntegerConsumerResult(1));
1546         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1547         verify(mMockPointingAppController).startSatelliteTransmissionUpdates(any(Message.class));
1548         verify(mMockPointingAppController).setStartedSatelliteTransmissionUpdates(eq(true));
1549 
1550         resetSatelliteControllerUT();
1551         provisionSatelliteService();
1552         mIIntegerConsumerResults.clear();
1553         setUpResponseForStartSatelliteTransmissionUpdates(SATELLITE_RESULT_INVALID_TELEPHONY_STATE);
1554         mSatelliteControllerUT.startSatelliteTransmissionUpdates(mIIntegerConsumer,
1555                 mStartTransmissionUpdateCallback);
1556         processAllMessages();
1557         assertTrue(waitForIIntegerConsumerResult(1));
1558         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
1559                 (long) mIIntegerConsumerResults.get(0));
1560         verify(mMockPointingAppController).unregisterForSatelliteTransmissionUpdates(anyInt(),
1561                 any(), eq(mStartTransmissionUpdateCallback));
1562         verify(mMockPointingAppController).setStartedSatelliteTransmissionUpdates(eq(false));
1563     }
1564 
1565     @Test
testStopSatelliteTransmissionUpdates()1566     public void testStopSatelliteTransmissionUpdates() {
1567         resetSatelliteControllerUT();
1568         mIIntegerConsumerResults.clear();
1569         provisionSatelliteService();
1570         setUpResponseForStopSatelliteTransmissionUpdates(SATELLITE_RESULT_SUCCESS);
1571         mSatelliteControllerUT.stopSatelliteTransmissionUpdates(mIIntegerConsumer,
1572                 mStopTransmissionUpdateCallback);
1573         verify(mMockPointingAppController).unregisterForSatelliteTransmissionUpdates(anyInt(),
1574                 any(), eq(mStopTransmissionUpdateCallback));
1575         processAllMessages();
1576         assertTrue(waitForIIntegerConsumerResult(1));
1577         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1578         verify(mMockPointingAppController).stopSatelliteTransmissionUpdates(any(Message.class));
1579 
1580         resetSatelliteControllerUT();
1581         provisionSatelliteService();
1582         mIIntegerConsumerResults.clear();
1583         setUpResponseForStopSatelliteTransmissionUpdates(SATELLITE_RESULT_INVALID_TELEPHONY_STATE);
1584         mSatelliteControllerUT.stopSatelliteTransmissionUpdates(mIIntegerConsumer,
1585                 mStopTransmissionUpdateCallback);
1586         verify(mMockPointingAppController, times(2)).unregisterForSatelliteTransmissionUpdates(
1587                 anyInt(), any(), eq(mStopTransmissionUpdateCallback));
1588         processAllMessages();
1589         verify(mMockPointingAppController, times(2)).stopSatelliteTransmissionUpdates(
1590                 any(Message.class));
1591         assertTrue(waitForIIntegerConsumerResult(1));
1592         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
1593                 (long) mIIntegerConsumerResults.get(0));
1594     }
1595 
1596     @Test
testRequestIsDemoModeEnabled()1597     public void testRequestIsDemoModeEnabled() {
1598         mIsDemoModeEnabledSemaphore.drainPermits();
1599         resetSatelliteControllerUT();
1600         mSatelliteControllerUT.requestIsDemoModeEnabled(mIsDemoModeEnabledReceiver);
1601         assertTrue(waitForRequestIsDemoModeEnabledResult(1));
1602         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE, mQueriedIsDemoModeEnabledResultCode);
1603         assertFalse(mQueriedIsDemoModeEnabled);
1604 
1605         resetSatelliteControllerUT();
1606         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1607         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1608         mSatelliteControllerUT.requestIsDemoModeEnabled(mIsDemoModeEnabledReceiver);
1609         assertTrue(waitForRequestIsDemoModeEnabledResult(1));
1610         assertEquals(SATELLITE_RESULT_NOT_SUPPORTED, mQueriedIsDemoModeEnabledResultCode);
1611         assertFalse(mQueriedIsDemoModeEnabled);
1612 
1613         resetSatelliteControllerUT();
1614         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1615         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1616         mSatelliteControllerUT.requestIsDemoModeEnabled(mIsDemoModeEnabledReceiver);
1617         assertTrue(waitForRequestIsDemoModeEnabledResult(1));
1618         assertEquals(SATELLITE_RESULT_SERVICE_NOT_PROVISIONED, mQueriedIsDemoModeEnabledResultCode);
1619         assertFalse(mQueriedIsDemoModeEnabled);
1620 
1621         resetSatelliteControllerUT();
1622         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1623         setUpResponseForRequestIsSatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1624         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1625         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1626         mSatelliteControllerUT.requestIsDemoModeEnabled(mIsDemoModeEnabledReceiver);
1627         assertTrue(waitForRequestIsDemoModeEnabledResult(1));
1628         assertEquals(SATELLITE_RESULT_SERVICE_NOT_PROVISIONED, mQueriedIsDemoModeEnabledResultCode);
1629         assertFalse(mQueriedIsDemoModeEnabled);
1630 
1631         resetSatelliteControllerUT();
1632         boolean isDemoModeEnabled = mSatelliteControllerUT.isDemoModeEnabled();
1633         provisionSatelliteService();
1634         mSatelliteControllerUT.requestIsDemoModeEnabled(mIsDemoModeEnabledReceiver);
1635         assertTrue(waitForRequestIsDemoModeEnabledResult(1));
1636         assertEquals(SATELLITE_RESULT_SUCCESS, mQueriedIsDemoModeEnabledResultCode);
1637         assertEquals(isDemoModeEnabled, mQueriedIsDemoModeEnabled);
1638     }
1639 
1640     @Test
testIsSatelliteEnabled()1641     public void testIsSatelliteEnabled() {
1642         logd("testIsSatelliteEnabled: starting");
1643         assertFalse(mSatelliteControllerUT.isSatelliteEnabledOrBeingEnabled());
1644         setUpResponseForRequestIsSatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
1645         mIsSatelliteEnabledSemaphore.drainPermits();
1646         mSatelliteControllerUT.requestIsSatelliteEnabled(mIsSatelliteEnabledReceiver);
1647         processAllMessages();
1648         assertTrue(waitForRequestIsSatelliteEnabledResult(1));
1649         assertEquals(
1650                 SATELLITE_RESULT_INVALID_TELEPHONY_STATE, mQueriedIsSatelliteEnabledResultCode);
1651 
1652 
1653         logd("testIsSatelliteEnabled: setUpResponseForRequestIsSatelliteSupported");
1654         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1655         logd("testIsSatelliteEnabled: verifySatelliteSupported");
1656         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1657         mSatelliteControllerUT.requestIsSatelliteEnabled(mIsSatelliteEnabledReceiver);
1658         processAllMessages();
1659         assertEquals(SATELLITE_RESULT_SUCCESS, mQueriedIsSatelliteEnabledResultCode);
1660         assertEquals(mSatelliteControllerUT.isSatelliteEnabledOrBeingEnabled(),
1661                 mQueriedIsSatelliteEnabled);
1662     }
1663 
1664     @Test
testOnSatelliteServiceConnected()1665     public void testOnSatelliteServiceConnected() {
1666         verifySatelliteSupported(false, SATELLITE_RESULT_RADIO_NOT_AVAILABLE);
1667         verifySatelliteEnabled(false, SATELLITE_RESULT_INVALID_TELEPHONY_STATE);
1668 
1669         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1670         setUpResponseForRequestIsSatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
1671         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
1672 
1673         setUpResponseForRequestIsSatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1674         mSatelliteControllerUT.onSatelliteServiceConnected();
1675         processAllMessages();
1676 
1677         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1678         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
1679         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
1680     }
1681 
1682     @Test
testRegisterForSatelliteModemStateChanged()1683     public void testRegisterForSatelliteModemStateChanged() {
1684         ISatelliteModemStateCallback callback = new ISatelliteModemStateCallback.Stub() {
1685             @Override
1686             public void onSatelliteModemStateChanged(int state) {
1687                 logd("onSatelliteModemStateChanged: state=" + state);
1688             }
1689 
1690             @Override
1691             public void onEmergencyModeChanged(boolean isEmergency) {
1692                 logd("onEmergencyModeChanged: emergency=" + isEmergency);
1693             }
1694 
1695             @Override
1696             public void onRegistrationFailure(int causeCode) {
1697                 logd("onRegistrationFailure: causeCode=" + causeCode);
1698             }
1699 
1700             @Override
1701             public void onTerrestrialNetworkAvailableChanged(boolean isAvailable) {
1702                 logd("onTerrestrialNetworkAvailableChanged: isAvailable=" + isAvailable);
1703             }
1704         };
1705         int errorCode = mSatelliteControllerUT.registerForSatelliteModemStateChanged(callback);
1706         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE, errorCode);
1707         verify(mMockSatelliteSessionController, never())
1708                 .registerForSatelliteModemStateChanged(callback);
1709 
1710         resetSatelliteControllerUTToSupportedAndProvisionedState();
1711         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
1712 
1713         errorCode = mSatelliteControllerUT.registerForSatelliteModemStateChanged(callback);
1714         assertEquals(SATELLITE_RESULT_SUCCESS, errorCode);
1715         verify(mMockSatelliteSessionController).registerForSatelliteModemStateChanged(callback);
1716     }
1717 
1718     @Test
testUnregisterForSatelliteModemStateChanged()1719     public void testUnregisterForSatelliteModemStateChanged() {
1720         ISatelliteModemStateCallback callback = new ISatelliteModemStateCallback.Stub() {
1721             @Override
1722             public void onSatelliteModemStateChanged(int state) {
1723                 logd("onSatelliteModemStateChanged: state=" + state);
1724             }
1725 
1726             @Override
1727             public void onEmergencyModeChanged(boolean isEmergency) {
1728                 logd("onEmergencyModeChanged: emergency=" + isEmergency);
1729             }
1730 
1731             @Override
1732             public void onRegistrationFailure(int causeCode) {
1733                 logd("onRegistrationFailure: causeCode=" + causeCode);
1734             }
1735 
1736             @Override
1737             public void onTerrestrialNetworkAvailableChanged(boolean isAvailable) {
1738                 logd("onTerrestrialNetworkAvailableChanged: isAvailable=" + isAvailable);
1739             }
1740         };
1741         mSatelliteControllerUT.unregisterForModemStateChanged(callback);
1742         verify(mMockSatelliteSessionController, never())
1743                 .unregisterForSatelliteModemStateChanged(callback);
1744 
1745         resetSatelliteControllerUTToSupportedAndProvisionedState();
1746         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
1747         mSatelliteControllerUT.unregisterForModemStateChanged(callback);
1748         verify(mMockSatelliteSessionController).unregisterForSatelliteModemStateChanged(callback);
1749     }
1750 
1751     @Test
testRegisterForSatelliteProvisionStateChanged()1752     public void testRegisterForSatelliteProvisionStateChanged() {
1753         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
1754         Semaphore semaphore = new Semaphore(0);
1755         ISatelliteProvisionStateCallback callback =
1756                 new ISatelliteProvisionStateCallback.Stub() {
1757                     @Override
1758                     public void onSatelliteProvisionStateChanged(boolean provisioned) {
1759                         logd("onSatelliteProvisionStateChanged: provisioned=" + provisioned);
1760                         try {
1761                             semaphore.release();
1762                         } catch (Exception ex) {
1763                             loge("onSatelliteProvisionStateChanged: Got exception in releasing "
1764                                     + "semaphore, ex=" + ex);
1765                         }
1766                     }
1767 
1768                     @Override
1769                     public void onSatelliteSubscriptionProvisionStateChanged(
1770                             List<SatelliteSubscriberProvisionStatus> status) {
1771                         logd("onSatelliteSubscriptionProvisionStateChanged: " + status);
1772                     }
1773                 };
1774         int errorCode = mSatelliteControllerUT.registerForSatelliteProvisionStateChanged(callback);
1775         assertEquals(SATELLITE_RESULT_SUCCESS, errorCode);
1776 
1777         resetSatelliteControllerUT();
1778         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1779         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1780         errorCode = mSatelliteControllerUT.registerForSatelliteProvisionStateChanged(callback);
1781         processAllMessages();
1782         assertTrue(waitForForEvents(
1783                 semaphore, 1, "testRegisterForSatelliteProvisionStateChanged"));
1784         assertEquals(SATELLITE_RESULT_SUCCESS, errorCode);
1785 
1786         try {
1787             setSatelliteSubscriberTesting(true);
1788         } catch (Exception ex) {
1789             fail("provisionSatelliteService.setSatelliteSubscriberTesting: ex=" + ex);
1790         }
1791         doReturn(true).when(mMockSubscriptionManagerService).isSatelliteProvisionedForNonIpDatagram(
1792                 anyInt());
1793 
1794         String mText = "This is test provision data.";
1795         byte[] testProvisionData = mText.getBytes();
1796         CancellationSignal cancellationSignal = new CancellationSignal();
1797         ICancellationSignal cancelRemote = null;
1798         mIIntegerConsumerResults.clear();
1799         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
1800                 TEST_SATELLITE_TOKEN,
1801                 testProvisionData, mIIntegerConsumer);
1802         processAllMessages();
1803         assertTrue(waitForForEvents(
1804                 semaphore, 1, "testRegisterForSatelliteProvisionStateChanged"));
1805         mSatelliteControllerUT.unregisterForSatelliteProvisionStateChanged(callback);
1806         semaphore.drainPermits();
1807         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
1808                 TEST_SATELLITE_TOKEN,
1809                 testProvisionData, mIIntegerConsumer);
1810         processAllMessages();
1811         assertFalse(waitForForEvents(
1812                 semaphore, 1, "testRegisterForSatelliteProvisionStateChanged"));
1813     }
1814 
1815     @Test
testRegisterForSatelliteDatagram()1816     public void testRegisterForSatelliteDatagram() {
1817         ISatelliteDatagramCallback callback =
1818                 new ISatelliteDatagramCallback.Stub() {
1819                     @Override
1820                     public void onSatelliteDatagramReceived(long datagramId,
1821                             @NonNull SatelliteDatagram datagram, int pendingCount,
1822                             @NonNull IVoidConsumer internalAck) {
1823                         logd("onSatelliteDatagramReceived");
1824                     }
1825                 };
1826         when(mMockDatagramController.registerForSatelliteDatagram(anyInt(), eq(callback)))
1827                 .thenReturn(SATELLITE_RESULT_SUCCESS);
1828         int errorCode = mSatelliteControllerUT.registerForIncomingDatagram(callback);
1829         assertEquals(SATELLITE_RESULT_SUCCESS, errorCode);
1830         verify(mMockDatagramController).registerForSatelliteDatagram(anyInt(), eq(callback));
1831     }
1832 
1833     @Test
testUnregisterForSatelliteDatagram()1834     public void testUnregisterForSatelliteDatagram() {
1835         ISatelliteDatagramCallback callback =
1836                 new ISatelliteDatagramCallback.Stub() {
1837                     @Override
1838                     public void onSatelliteDatagramReceived(long datagramId,
1839                             @NonNull SatelliteDatagram datagram, int pendingCount,
1840                             @NonNull IVoidConsumer internalAck) {
1841                         logd("onSatelliteDatagramReceived");
1842                     }
1843                 };
1844         doNothing().when(mMockDatagramController)
1845                 .unregisterForSatelliteDatagram(anyInt(), eq(callback));
1846         mSatelliteControllerUT.unregisterForIncomingDatagram(callback);
1847         verify(mMockDatagramController).unregisterForSatelliteDatagram(anyInt(), eq(callback));
1848     }
1849 
1850     @Test
testSendSatelliteDatagram()1851     public void testSendSatelliteDatagram() {
1852         String mText = "This is a test datagram message from user";
1853         SatelliteDatagram datagram = new SatelliteDatagram(mText.getBytes());
1854 
1855         int[] sosDatagramTypes = {SatelliteManager.DATAGRAM_TYPE_SOS_MESSAGE,
1856                 SatelliteManager.DATAGRAM_TYPE_LAST_SOS_MESSAGE_STILL_NEED_HELP,
1857                 SatelliteManager.DATAGRAM_TYPE_LAST_SOS_MESSAGE_NO_HELP_NEEDED};
1858         for (int datagramType : sosDatagramTypes) {
1859             mSatelliteControllerUT =
1860                     new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
1861             mIIntegerConsumerSemaphore.drainPermits();
1862             mIIntegerConsumerResults.clear();
1863             clearInvocations(mMockDatagramController);
1864             clearInvocations(mMockPointingAppController);
1865 
1866             mSatelliteControllerUT.sendDatagram(datagramType, datagram, true,
1867                     mIIntegerConsumer);
1868             processAllMessages();
1869             assertTrue(waitForIIntegerConsumerResult(1));
1870             assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
1871                     (long) mIIntegerConsumerResults.get(0));
1872             verify(mMockDatagramController, never()).sendSatelliteDatagram(anyInt(),
1873                     eq(datagramType), eq(datagram), eq(true), any());
1874 
1875             mIIntegerConsumerResults.clear();
1876             setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1877             verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1878             setProvisionedState(false);
1879             processAllMessages();
1880             verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1881             mSatelliteControllerUT.sendDatagram(datagramType, datagram, true,
1882                     mIIntegerConsumer);
1883             processAllMessages();
1884             assertTrue(waitForIIntegerConsumerResult(1));
1885             assertEquals(SATELLITE_RESULT_SERVICE_NOT_PROVISIONED,
1886                     (long) mIIntegerConsumerResults.get(0));
1887             verify(mMockDatagramController, never()).sendSatelliteDatagram(anyInt(),
1888                     eq(datagramType), eq(datagram), eq(true), any());
1889 
1890             mIIntegerConsumerResults.clear();
1891             setProvisionedState(true);
1892             processAllMessages();
1893             verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
1894             mSatelliteControllerUT.sendDatagram(datagramType, datagram, true,
1895                     mIIntegerConsumer);
1896             processAllMessages();
1897             assertFalse(waitForIIntegerConsumerResult(1));
1898             verify(mMockDatagramController, times(1)).sendSatelliteDatagram(anyInt(),
1899                     eq(datagramType), eq(datagram), eq(true), any());
1900             verify(mMockPointingAppController, times(1)).startPointingUI(eq(true), anyBoolean(),
1901                     anyBoolean());
1902         }
1903     }
1904 
1905     @Test
testPollPendingSatelliteDatagrams()1906     public void testPollPendingSatelliteDatagrams() {
1907         mIIntegerConsumerResults.clear();
1908         mSatelliteControllerUT.pollPendingDatagrams(mIIntegerConsumer);
1909         processAllMessages();
1910         assertTrue(waitForIIntegerConsumerResult(1));
1911         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
1912                 (long) mIIntegerConsumerResults.get(0));
1913         verify(mMockDatagramController, never()).pollPendingSatelliteDatagrams(anyInt(), any());
1914 
1915         mIIntegerConsumerResults.clear();
1916         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1917         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1918         setProvisionedState(false);
1919         processAllMessages();
1920         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1921         mSatelliteControllerUT.pollPendingDatagrams(mIIntegerConsumer);
1922         processAllMessages();
1923         assertTrue(waitForIIntegerConsumerResult(1));
1924         assertEquals(SATELLITE_RESULT_SERVICE_NOT_PROVISIONED,
1925                 (long) mIIntegerConsumerResults.get(0));
1926         verify(mMockDatagramController, never()).pollPendingSatelliteDatagrams(anyInt(), any());
1927 
1928         mIIntegerConsumerResults.clear();
1929         setProvisionedState(true);
1930         processAllMessages();
1931         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
1932         mSatelliteControllerUT.pollPendingDatagrams(mIIntegerConsumer);
1933         processAllMessages();
1934         assertFalse(waitForIIntegerConsumerResult(1));
1935         verify(mMockDatagramController, times(1)).pollPendingSatelliteDatagrams(anyInt(), any());
1936     }
1937 
1938     @Test
testProvisionSatelliteService()1939     public void testProvisionSatelliteService() {
1940         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(false);
1941 
1942         String mText = "This is test provision data.";
1943         byte[] testProvisionData = mText.getBytes();
1944         CancellationSignal cancellationSignal = new CancellationSignal();
1945         ICancellationSignal cancelRemote = null;
1946         mIIntegerConsumerResults.clear();
1947         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
1948                 TEST_SATELLITE_TOKEN,
1949                 testProvisionData, mIIntegerConsumer);
1950         processAllMessages();
1951         assertTrue(waitForIIntegerConsumerResult(1));
1952         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
1953                 (long) mIIntegerConsumerResults.get(0));
1954         assertNull(cancelRemote);
1955 
1956         resetSatelliteControllerUT();
1957         mIIntegerConsumerResults.clear();
1958         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1959         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
1960         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
1961                 TEST_SATELLITE_TOKEN,
1962                 testProvisionData, mIIntegerConsumer);
1963         processAllMessages();
1964         assertTrue(waitForIIntegerConsumerResult(1));
1965         assertEquals(SATELLITE_RESULT_NOT_SUPPORTED, (long) mIIntegerConsumerResults.get(0));
1966         assertNull(cancelRemote);
1967 
1968         resetSatelliteControllerUT();
1969         mIIntegerConsumerResults.clear();
1970         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1971         setUpResponseForRequestIsSatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1972         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1973         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1974         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
1975                 TEST_SATELLITE_TOKEN,
1976                 testProvisionData, mIIntegerConsumer);
1977         processAllMessages();
1978         assertTrue(waitForIIntegerConsumerResult(1));
1979         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1980         assertNotNull(cancelRemote);
1981         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
1982 
1983         // Send provision request again after the device is successfully provisioned
1984         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
1985                 TEST_SATELLITE_TOKEN,
1986                 testProvisionData, mIIntegerConsumer);
1987         processAllMessages();
1988         assertTrue(waitForIIntegerConsumerResult(1));
1989         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
1990         assertNull(cancelRemote);
1991 
1992         resetSatelliteControllerUT();
1993         mIIntegerConsumerResults.clear();
1994         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1995         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
1996         setUpResponseForRequestIsSatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1997         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
1998         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
1999                 TEST_NEXT_SATELLITE_TOKEN, testProvisionData, mIIntegerConsumer);
2000         cancellationSignal.setRemote(cancelRemote);
2001         cancellationSignal.cancel();
2002         processAllMessages();
2003         assertTrue(waitForIIntegerConsumerResult(1));
2004         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2005 
2006         resetSatelliteControllerUT();
2007         mIIntegerConsumerResults.clear();
2008         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2009         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2010         setUpResponseForRequestIsSatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
2011         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
2012         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
2013                 TEST_SATELLITE_TOKEN,
2014                 testProvisionData, mIIntegerConsumer);
2015         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
2016                 TEST_NEXT_SATELLITE_TOKEN,
2017                 testProvisionData, mIIntegerConsumer);
2018         processAllMessages();
2019         assertTrue(waitForIIntegerConsumerResult(1));
2020         assertEquals(SATELLITE_RESULT_SERVICE_PROVISION_IN_PROGRESS,
2021                 (long) mIIntegerConsumerResults.get(0));
2022     }
2023 
2024     @Test
testDeprovisionSatelliteService()2025     public void testDeprovisionSatelliteService() {
2026         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(false);
2027         mIIntegerConsumerSemaphore.drainPermits();
2028         mIIntegerConsumerResults.clear();
2029         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
2030         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
2031         mSatelliteControllerUT.deprovisionSatelliteService(
2032                 TEST_SATELLITE_TOKEN, mIIntegerConsumer);
2033         processAllMessages();
2034         assertTrue(waitForIIntegerConsumerResult(1));
2035         assertEquals(SATELLITE_RESULT_NOT_SUPPORTED, (long) mIIntegerConsumerResults.get(0));
2036 
2037         resetSatelliteControllerUT();
2038         mIIntegerConsumerResults.clear();
2039         mSatelliteControllerUT.deprovisionSatelliteService(
2040                 TEST_SATELLITE_TOKEN, mIIntegerConsumer);
2041         processAllMessages();
2042         assertTrue(waitForIIntegerConsumerResult(1));
2043         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE,
2044                 (long) mIIntegerConsumerResults.get(0));
2045 
2046         resetSatelliteControllerUT();
2047         mIIntegerConsumerResults.clear();
2048         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2049         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2050         mSatelliteControllerUT.deprovisionSatelliteService(
2051                 TEST_SATELLITE_TOKEN, mIIntegerConsumer);
2052         processAllMessages();
2053         assertTrue(waitForIIntegerConsumerResult(1));
2054         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2055 
2056         resetSatelliteControllerUT();
2057         mIIntegerConsumerResults.clear();
2058         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2059         setUpResponseForRequestIsSatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
2060         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2061         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
2062         mSatelliteControllerUT.deprovisionSatelliteService(
2063                 TEST_SATELLITE_TOKEN, mIIntegerConsumer);
2064         processAllMessages();
2065         assertTrue(waitForIIntegerConsumerResult(1));
2066         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2067 
2068         resetSatelliteControllerUT();
2069         provisionSatelliteService();
2070         mIIntegerConsumerResults.clear();
2071         mSatelliteControllerUT.deprovisionSatelliteService(
2072                 TEST_SATELLITE_TOKEN, mIIntegerConsumer);
2073         processAllMessages();
2074         assertTrue(waitForIIntegerConsumerResult(1));
2075         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2076         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
2077 
2078         resetSatelliteControllerUT();
2079         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2080         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2081         setProvisionedState(null);
2082         mIIntegerConsumerResults.clear();
2083         mSatelliteControllerUT.deprovisionSatelliteService(
2084                 TEST_SATELLITE_TOKEN, mIIntegerConsumer);
2085         processAllMessages();
2086         assertTrue(waitForIIntegerConsumerResult(1));
2087         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2088         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
2089     }
2090 
2091     @Test
testSupportedSatelliteServices()2092     public void testSupportedSatelliteServices() throws Exception {
2093         String[] satelliteProviderStrArray = {"00101", "00102"};
2094         mContextFixture.putStringArrayResource(
2095                 R.array.config_satellite_providers, satelliteProviderStrArray);
2096         int[] expectedSupportedServices2 = {2};
2097         int[] expectedSupportedServices3 = {1, 3};
2098         int[] defaultSupportedServices = {5, 6};
2099         PersistableBundle carrierSupportedSatelliteServicesPerProvider = new PersistableBundle();
2100         carrierSupportedSatelliteServicesPerProvider.putIntArray(
2101                 "00102", expectedSupportedServices2);
2102         carrierSupportedSatelliteServicesPerProvider.putIntArray(
2103                 "00103", expectedSupportedServices3);
2104         String[] expectedSupportedSatellitePlmns = {"00102", "00103"};
2105         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
2106                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
2107                 carrierSupportedSatelliteServicesPerProvider);
2108         mCarrierConfigBundle.putIntArray(
2109                 CarrierConfigManager.KEY_CARRIER_ROAMING_SATELLITE_DEFAULT_SERVICES_INT_ARRAY,
2110                 defaultSupportedServices);
2111         TestSatelliteController testSatelliteController =
2112                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
2113 
2114         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
2115                 true);
2116         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
2117                 : mCarrierConfigChangedListenerList) {
2118             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
2119                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
2120             );
2121         }
2122         processAllMessages();
2123 
2124         List<String> satellitePlmnList = testSatelliteController.getSatellitePlmnsForCarrier(
2125                 SUB_ID);
2126         assertArrayEquals(expectedSupportedSatellitePlmns, satellitePlmnList.stream().toArray());
2127         List<Integer> supportedSatelliteServices =
2128                 mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(SUB_ID, "00102");
2129         // "00101" should return carrier config assigned value, though it is in allowed list.
2130         assertArrayEquals(expectedSupportedServices2, supportedSatelliteServices.stream()
2131                 .mapToInt(Integer::intValue)
2132                 .toArray());
2133         supportedSatelliteServices =
2134                 mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(SUB_ID, "00103");
2135         assertArrayEquals(expectedSupportedServices3, supportedSatelliteServices.stream()
2136                 .mapToInt(Integer::intValue)
2137                 .toArray());
2138         // "00104", and "00105" should return default supported service.
2139         supportedSatelliteServices =
2140                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID, "00104");
2141         assertArrayEquals(defaultSupportedServices, supportedSatelliteServices.stream()
2142                 .mapToInt(Integer::intValue)
2143                 .toArray());
2144         supportedSatelliteServices =
2145                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID, "00105");
2146         assertArrayEquals(defaultSupportedServices, supportedSatelliteServices.stream()
2147                 .mapToInt(Integer::intValue)
2148                 .toArray());
2149 
2150         // Subscriptions changed
2151         int[] newActiveSubIds = {SUB_ID1};
2152         doReturn(newActiveSubIds).when(mMockSubscriptionManagerService).getActiveSubIdList(true);
2153         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
2154                 : mCarrierConfigChangedListenerList) {
2155             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
2156                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
2157             );
2158         }
2159         processAllMessages();
2160 
2161         satellitePlmnList = testSatelliteController.getSatellitePlmnsForCarrier(SUB_ID);
2162         assertTrue(satellitePlmnList.isEmpty());
2163         // "00102" and "00103" should return default supported service for SUB_ID.
2164         supportedSatelliteServices =
2165                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID, "00102");
2166         assertArrayEquals(defaultSupportedServices, supportedSatelliteServices.stream()
2167                 .mapToInt(Integer::intValue)
2168                 .toArray());
2169         supportedSatelliteServices =
2170                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID, "00103");
2171         assertArrayEquals(defaultSupportedServices, supportedSatelliteServices.stream()
2172                 .mapToInt(Integer::intValue)
2173                 .toArray());
2174         // "00104", and "00105" should return default supported service for SUB_ID.
2175         supportedSatelliteServices =
2176                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID, "00104");
2177         assertArrayEquals(defaultSupportedServices, supportedSatelliteServices.stream()
2178                 .mapToInt(Integer::intValue)
2179                 .toArray());
2180         supportedSatelliteServices =
2181                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID, "00105");
2182         assertArrayEquals(defaultSupportedServices, supportedSatelliteServices.stream()
2183                 .mapToInt(Integer::intValue)
2184                 .toArray());
2185 
2186         supportedSatelliteServices =
2187                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID1, "00102");
2188         assertNotNull(supportedSatelliteServices);
2189         assertArrayEquals(expectedSupportedServices2, supportedSatelliteServices.stream()
2190                 .mapToInt(Integer::intValue)
2191                 .toArray());
2192 
2193         supportedSatelliteServices =
2194                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID1, "00103");
2195         assertArrayEquals(expectedSupportedServices3, supportedSatelliteServices.stream()
2196                 .mapToInt(Integer::intValue)
2197                 .toArray());
2198         /* "00104", and "00105" should return default supported service. */
2199         supportedSatelliteServices =
2200                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID1, "00104");
2201         assertArrayEquals(defaultSupportedServices, supportedSatelliteServices.stream()
2202                 .mapToInt(Integer::intValue)
2203                 .toArray());
2204         supportedSatelliteServices =
2205                 testSatelliteController.getSupportedSatelliteServicesForPlmn(SUB_ID1, "00105");
2206         assertArrayEquals(defaultSupportedServices, supportedSatelliteServices.stream()
2207                 .mapToInt(Integer::intValue)
2208                 .toArray());
2209     }
2210 
2211     @Test
testConfigureSatellitePlmnOnCarrierConfigChanged()2212     public void testConfigureSatellitePlmnOnCarrierConfigChanged() {
2213         logd("testConfigureSatellitePlmnOnCarrierConfigChanged");
2214 
2215         String[] satelliteProviderStrArray =
2216                 {"00101", "00102", "00103", "00104", "00105"};
2217         List<String> satellitePlmnListFromOverlayConfig =
2218                 Arrays.stream(satelliteProviderStrArray).toList();
2219         mContextFixture.putStringArrayResource(
2220                 R.array.config_satellite_providers, satelliteProviderStrArray);
2221 
2222         /* Initially, the radio state is ON. In the constructor, satelliteController registers for
2223          the radio state changed events and immediately gets the radio state changed event as ON. */
2224         doReturn(false).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2225         mCarrierConfigChangedListenerList.clear();
2226         TestSatelliteController testSatelliteController =
2227                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
2228         processAllMessages();
2229         List<String> carrierPlmnList = testSatelliteController.getSatellitePlmnsForCarrier(
2230                 SUB_ID);
2231         verify(mPhone, never()).setSatellitePlmn(
2232                 anyInt(), anyList(), anyList(), any(Message.class));
2233         assertTrue(carrierPlmnList.isEmpty());
2234         reset(mMockSatelliteModemInterface);
2235 
2236         // Test setSatellitePlmn() when Carrier Config change event triggered.
2237         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
2238                 true);
2239         int[] supportedServices2 = {2};
2240         int[] supportedServices3 = {1, 3};
2241         PersistableBundle carrierSupportedSatelliteServicesPerProvider = new PersistableBundle();
2242         carrierSupportedSatelliteServicesPerProvider.putIntArray(
2243                 "00102", supportedServices2);
2244         carrierSupportedSatelliteServicesPerProvider.putIntArray(
2245                 "00103", supportedServices3);
2246         List<String> expectedCarrierPlmnList = Arrays.asList("00102", "00103");
2247 
2248         mCarrierConfigChangedListenerList.clear();
2249         when(mPhone.getSignalStrengthController()).thenReturn(mSignalStrengthController);
2250         when(mPhone.getDeviceStateMonitor()).thenReturn(mDeviceStateMonitor);
2251         testSatelliteController =
2252                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
2253 
2254         // Trigger carrier config changed with empty carrier supported satellite services.
2255         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
2256                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
2257                 new PersistableBundle());
2258         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
2259                 : mCarrierConfigChangedListenerList) {
2260             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
2261                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
2262             );
2263         }
2264         processAllMessages();
2265 
2266         carrierPlmnList = testSatelliteController.getSatellitePlmnsForCarrier(SUB_ID);
2267         assertTrue(carrierPlmnList.isEmpty());
2268         List<String> allSatellitePlmnList = SatelliteServiceUtils.mergeStrLists(
2269                 carrierPlmnList, satellitePlmnListFromOverlayConfig);
2270         verify(mPhone, times(1)).setSatellitePlmn(anyInt(),
2271                 eq(EMPTY_STRING_LIST), eq(allSatellitePlmnList), any(Message.class));
2272         reset(mMockSatelliteModemInterface);
2273         reset(mPhone);
2274 
2275         // Trigger carrier config changed with non-empty carrier supported satellite services.
2276         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
2277                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
2278                 carrierSupportedSatelliteServicesPerProvider);
2279         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
2280                 : mCarrierConfigChangedListenerList) {
2281             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
2282                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
2283             );
2284         }
2285         processAllMessages();
2286         carrierPlmnList = testSatelliteController.getSatellitePlmnsForCarrier(SUB_ID);
2287         allSatellitePlmnList = SatelliteServiceUtils.mergeStrLists(
2288                 carrierPlmnList, satellitePlmnListFromOverlayConfig);
2289         assertEquals(expectedCarrierPlmnList, carrierPlmnList);
2290         verify(mPhone, times(1)).setSatellitePlmn(anyInt(),
2291                 eq(carrierPlmnList), eq(allSatellitePlmnList), any(Message.class));
2292         reset(mMockSatelliteModemInterface);
2293         reset(mPhone);
2294 
2295          /* setSatellitePlmn() is called regardless whether satellite attach for carrier is
2296            supported. */
2297         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
2298                 false);
2299         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
2300                 : mCarrierConfigChangedListenerList) {
2301             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
2302                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
2303             );
2304         }
2305         processAllMessages();
2306         verify(mPhone, times(1)).setSatellitePlmn(anyInt(),
2307                 eq(carrierPlmnList), eq(allSatellitePlmnList), any(Message.class));
2308         reset(mMockSatelliteModemInterface);
2309         reset(mPhone);
2310 
2311         // Test empty config_satellite_providers and empty carrier PLMN list
2312         // allSatellitePlmnList is stored in shared preference, so plmns will not be removed
2313         mCarrierConfigChangedListenerList.clear();
2314         mContextFixture.putStringArrayResource(
2315                 R.array.config_satellite_providers, EMPTY_STRING_ARRAY);
2316         when(mPhone.getSignalStrengthController()).thenReturn(mSignalStrengthController);
2317         when(mPhone.getDeviceStateMonitor()).thenReturn(mDeviceStateMonitor);
2318         testSatelliteController =
2319                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
2320         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
2321                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
2322                 new PersistableBundle());
2323         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
2324                 : mCarrierConfigChangedListenerList) {
2325             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
2326                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
2327             );
2328         }
2329         processAllMessages();
2330         carrierPlmnList = testSatelliteController.getSatellitePlmnsForCarrier(SUB_ID);
2331         assertTrue(carrierPlmnList.isEmpty());
2332         verify(mPhone, times(1)).setSatellitePlmn(anyInt(),
2333                 eq(EMPTY_STRING_LIST), eq(allSatellitePlmnList), any(Message.class));
2334         reset(mMockSatelliteModemInterface);
2335         reset(mPhone);
2336     }
2337 
2338     @Test
testSatelliteCommunicationRestriction()2339     public void testSatelliteCommunicationRestriction() {
2340         mCarrierConfigBundle.putBoolean(
2341                 CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
2342         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
2343                 : mCarrierConfigChangedListenerList) {
2344             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
2345                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
2346             );
2347         }
2348         processAllMessages();
2349 
2350         // Remove restriction reason if exist
2351         mIIntegerConsumerResults.clear();
2352         reset(mMockSatelliteModemInterface);
2353         setUpResponseForRequestSetSatelliteEnabledForCarrier(true, SATELLITE_RESULT_SUCCESS);
2354         setUpResponseForRequestSetSatelliteEnabledForCarrier(false, SATELLITE_RESULT_SUCCESS);
2355         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2356         mSatelliteControllerUT.removeAttachRestrictionForCarrier(SUB_ID,
2357                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER, mIIntegerConsumer);
2358         mSatelliteControllerUT.removeAttachRestrictionForCarrier(SUB_ID,
2359                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION, mIIntegerConsumer);
2360         processAllMessages();
2361         assertTrue(waitForIIntegerConsumerResult(2));
2362 
2363         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2364         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(1));
2365 
2366         Set<Integer> restrictionSet =
2367                 mSatelliteControllerUT.getAttachRestrictionReasonsForCarrier(SUB_ID);
2368         assertTrue(!restrictionSet.contains(SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER));
2369         assertTrue(!restrictionSet.contains(
2370                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION));
2371 
2372         // Add satellite attach restriction reason by user
2373         mIIntegerConsumerResults.clear();
2374         reset(mMockSatelliteModemInterface);
2375         setUpResponseForRequestSetSatelliteEnabledForCarrier(false, SATELLITE_RESULT_SUCCESS);
2376         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2377         mSatelliteControllerUT.addAttachRestrictionForCarrier(SUB_ID,
2378                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER, mIIntegerConsumer);
2379         processAllMessages();
2380         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2381         verify(mPhone, never())
2382                 .setSatelliteEnabledForCarrier(anyInt(), anyBoolean(), any(Message.class));
2383         assertTrue(waitForIIntegerConsumerResult(1));
2384         restrictionSet =
2385                 mSatelliteControllerUT.getAttachRestrictionReasonsForCarrier(SUB_ID);
2386         assertTrue(restrictionSet.contains(SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER));
2387 
2388         // remove satellite restriction reason by user
2389         mIIntegerConsumerResults.clear();
2390         reset(mMockSatelliteModemInterface);
2391         setUpResponseForRequestSetSatelliteEnabledForCarrier(true, SATELLITE_RESULT_SUCCESS);
2392         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2393         mSatelliteControllerUT.removeAttachRestrictionForCarrier(SUB_ID,
2394                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER, mIIntegerConsumer);
2395         processAllMessages();
2396         assertTrue(waitForIIntegerConsumerResult(1));
2397         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2398         restrictionSet =
2399                 mSatelliteControllerUT.getAttachRestrictionReasonsForCarrier(SUB_ID);
2400         assertTrue(!restrictionSet.contains(SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER));
2401         verify(mPhone, times(1))
2402                 .setSatelliteEnabledForCarrier(anyInt(), anyBoolean(), any(Message.class));
2403 
2404         // Add satellite attach restriction reason by user
2405         mIIntegerConsumerResults.clear();
2406         reset(mMockSatelliteModemInterface);
2407         setUpResponseForRequestSetSatelliteEnabledForCarrier(false, SATELLITE_RESULT_SUCCESS);
2408         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2409         mSatelliteControllerUT.addAttachRestrictionForCarrier(SUB_ID,
2410                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER, mIIntegerConsumer);
2411         processAllMessages();
2412         assertTrue(waitForIIntegerConsumerResult(1));
2413         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2414         restrictionSet =
2415                 mSatelliteControllerUT.getAttachRestrictionReasonsForCarrier(SUB_ID);
2416         assertTrue(restrictionSet.contains(SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER));
2417         verify(mPhone, times(1))
2418                 .setSatelliteEnabledForCarrier(anyInt(), eq(false), any(Message.class));
2419 
2420         // add satellite attach restriction reason by geolocation
2421         mIIntegerConsumerResults.clear();
2422         reset(mMockSatelliteModemInterface);
2423         reset(mPhone);
2424         setUpResponseForRequestSetSatelliteEnabledForCarrier(false, SATELLITE_RESULT_SUCCESS);
2425         mSatelliteControllerUT.addAttachRestrictionForCarrier(SUB_ID,
2426                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION, mIIntegerConsumer);
2427         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2428         processAllMessages();
2429         assertTrue(waitForIIntegerConsumerResult(1));
2430         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2431         restrictionSet =
2432                 mSatelliteControllerUT.getAttachRestrictionReasonsForCarrier(SUB_ID);
2433         assertTrue(restrictionSet.contains(SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION));
2434         verify(mPhone, never())
2435                 .setSatelliteEnabledForCarrier(anyInt(), anyBoolean(), any(Message.class));
2436 
2437         // remove satellite attach restriction reason by geolocation
2438         mIIntegerConsumerResults.clear();
2439         reset(mMockSatelliteModemInterface);
2440         setUpResponseForRequestSetSatelliteEnabledForCarrier(true, SATELLITE_RESULT_SUCCESS);
2441         mSatelliteControllerUT.removeAttachRestrictionForCarrier(SUB_ID,
2442                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION, mIIntegerConsumer);
2443         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2444         processAllMessages();
2445         assertTrue(waitForIIntegerConsumerResult(1));
2446         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2447         restrictionSet =
2448                 mSatelliteControllerUT.getAttachRestrictionReasonsForCarrier(SUB_ID);
2449         assertTrue(!restrictionSet.contains(
2450                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_GEOLOCATION));
2451         verify(mPhone, never())
2452                 .setSatelliteEnabledForCarrier(anyInt(), anyBoolean(), any(Message.class));
2453 
2454         // remove satellite restriction reason by user
2455         mIIntegerConsumerResults.clear();
2456         reset(mMockSatelliteModemInterface);
2457         setUpResponseForRequestSetSatelliteEnabledForCarrier(true, SATELLITE_RESULT_SUCCESS);
2458         mSatelliteControllerUT.removeAttachRestrictionForCarrier(SUB_ID,
2459                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER, mIIntegerConsumer);
2460         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2461         processAllMessages();
2462         assertTrue(waitForIIntegerConsumerResult(1));
2463         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2464         restrictionSet =
2465                 mSatelliteControllerUT.getAttachRestrictionReasonsForCarrier(SUB_ID);
2466         assertTrue(!restrictionSet.contains(SATELLITE_COMMUNICATION_RESTRICTION_REASON_USER));
2467         verify(mPhone, times(1))
2468                 .setSatelliteEnabledForCarrier(anyInt(), eq(true), any(Message.class));
2469         reset(mMockSatelliteModemInterface);
2470     }
2471 
2472     @Test
testIsSatelliteAttachRequired()2473     public void testIsSatelliteAttachRequired() {
2474         TestSatelliteController satelliteController =
2475                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
2476         mSatelliteCapabilitiesSemaphore.drainPermits();
2477         satelliteController.requestSatelliteCapabilities(mSatelliteCapabilitiesReceiver);
2478         processAllMessages();
2479         assertTrue(waitForRequestSatelliteCapabilitiesResult(1));
2480         assertEquals(
2481                 SATELLITE_RESULT_INVALID_TELEPHONY_STATE, mQueriedSatelliteCapabilitiesResultCode);
2482         assertFalse(satelliteController.isSatelliteAttachRequired());
2483 
2484         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2485         setUpResponseForRequestSatelliteCapabilities(
2486                 mEmptySatelliteCapabilities, SATELLITE_RESULT_SUCCESS);
2487         satelliteController =
2488                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
2489         verifySatelliteSupported(satelliteController, true, SATELLITE_RESULT_SUCCESS);
2490         mSatelliteCapabilitiesSemaphore.drainPermits();
2491         satelliteController.requestSatelliteCapabilities(mSatelliteCapabilitiesReceiver);
2492         processAllMessages();
2493         assertTrue(waitForRequestSatelliteCapabilitiesResult(1));
2494         assertEquals(SATELLITE_RESULT_SUCCESS, mQueriedSatelliteCapabilitiesResultCode);
2495         assertEquals(mEmptySatelliteCapabilities, mQueriedSatelliteCapabilities);
2496         assertEquals(SatelliteManager.NT_RADIO_TECHNOLOGY_UNKNOWN,
2497                 mSatelliteControllerUT.getSupportedNtnRadioTechnology());
2498 
2499         assertFalse(satelliteController.isSatelliteAttachRequired());
2500 
2501         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2502         setUpResponseForRequestSatelliteCapabilities(
2503                 mSatelliteCapabilities, SATELLITE_RESULT_SUCCESS);
2504         satelliteController =
2505                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
2506         verifySatelliteSupported(satelliteController, true, SATELLITE_RESULT_SUCCESS);
2507         mSatelliteCapabilitiesSemaphore.drainPermits();
2508         satelliteController.requestSatelliteCapabilities(mSatelliteCapabilitiesReceiver);
2509         processAllMessages();
2510         assertTrue(waitForRequestSatelliteCapabilitiesResult(1));
2511         assertEquals(SATELLITE_RESULT_SUCCESS, mQueriedSatelliteCapabilitiesResultCode);
2512         assertEquals(mSatelliteCapabilities, mQueriedSatelliteCapabilities);
2513         assertTrue(
2514                 mQueriedSatelliteCapabilities.getSupportedRadioTechnologies().contains(
2515                         satelliteController.getSupportedNtnRadioTechnology()));
2516         assertEquals(mQueriedSatelliteCapabilities.getMaxBytesPerOutgoingDatagram(), 255);
2517         assertTrue(satelliteController.isSatelliteAttachRequired());
2518     }
2519 
2520     @Test
testSatelliteModemStateChanged()2521     public void testSatelliteModemStateChanged() {
2522         clearInvocations(mMockSatelliteSessionController);
2523         clearInvocations(mMockDatagramController);
2524         sendSatelliteModemStateChangedEvent(SATELLITE_MODEM_STATE_CONNECTED, null);
2525         processAllMessages();
2526         verify(mMockSatelliteSessionController, times(0)).onSatelliteModemStateChanged(
2527                 SATELLITE_MODEM_STATE_CONNECTED);
2528 
2529         resetSatelliteControllerUTToSupportedAndProvisionedState();
2530         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
2531         clearInvocations(mMockSatelliteSessionController);
2532         clearInvocations(mMockDatagramController);
2533         sendSatelliteModemStateChangedEvent(SATELLITE_MODEM_STATE_UNAVAILABLE, null);
2534         processAllMessages();
2535         verify(mMockSatelliteSessionController, times(1)).onSatelliteModemStateChanged(
2536                 eq(SATELLITE_MODEM_STATE_OFF));
2537 
2538         clearInvocations(mMockSatelliteSessionController);
2539         clearInvocations(mMockDatagramController);
2540         mSatelliteControllerUT.isSatelliteBeingDisabled = true;
2541         sendSatelliteModemStateChangedEvent(SATELLITE_MODEM_STATE_NOT_CONNECTED, null);
2542         processAllMessages();
2543         verify(mMockSatelliteSessionController, times(1)).onSatelliteModemStateChanged(
2544                 SATELLITE_MODEM_STATE_NOT_CONNECTED);
2545 
2546         clearInvocations(mMockSatelliteSessionController);
2547         mSatelliteControllerUT.isSatelliteBeingDisabled = false;
2548         sendSatelliteModemStateChangedEvent(SATELLITE_MODEM_STATE_NOT_CONNECTED, null);
2549         processAllMessages();
2550         verify(mMockSatelliteSessionController, never()).onSatelliteModemStateChanged(
2551                 SATELLITE_MODEM_STATE_NOT_CONNECTED);
2552     }
2553 
2554     @Test
testRequestNtnSignalStrengthWithFeatureFlagEnabled()2555     public void testRequestNtnSignalStrengthWithFeatureFlagEnabled() {
2556         resetSatelliteControllerUT();
2557 
2558         mRequestNtnSignalStrengthSemaphore.drainPermits();
2559         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
2560         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
2561 
2562         @NtnSignalStrength.NtnSignalStrengthLevel int expectedLevel = NTN_SIGNAL_STRENGTH_GREAT;
2563         setUpResponseForRequestNtnSignalStrength(expectedLevel, SATELLITE_RESULT_SUCCESS);
2564         /* In case request is not successful, result should be NTN_SIGNAL_STRENGTH_NONE */
2565         verifyRequestNtnSignalStrength(NTN_SIGNAL_STRENGTH_NONE, SATELLITE_RESULT_NOT_SUPPORTED);
2566 
2567         resetSatelliteControllerUT();
2568         provisionSatelliteService();
2569 
2570         doReturn(false).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2571         setUpResponseForRequestNtnSignalStrength(expectedLevel, SATELLITE_RESULT_SUCCESS);
2572         verifyRequestNtnSignalStrength(NTN_SIGNAL_STRENGTH_NONE,
2573                 SATELLITE_RESULT_REQUEST_NOT_SUPPORTED);
2574 
2575         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2576         setUpResponseForRequestNtnSignalStrength(expectedLevel, SATELLITE_RESULT_SUCCESS);
2577         verifyRequestNtnSignalStrength(expectedLevel, SATELLITE_RESULT_SUCCESS);
2578 
2579         resetSatelliteControllerUT();
2580         provisionSatelliteService();
2581         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2582         // reset cache to NTN_SIGNAL_STRENGTH_NONE
2583         sendNtnSignalStrengthChangedEvent(NTN_SIGNAL_STRENGTH_NONE, null);
2584         processAllMessages();
2585         expectedLevel = NTN_SIGNAL_STRENGTH_POOR;
2586         setUpResponseForRequestNtnSignalStrength(expectedLevel, SATELLITE_RESULT_SUCCESS);
2587         verifyRequestNtnSignalStrength(expectedLevel, SATELLITE_RESULT_SUCCESS);
2588     }
2589 
2590     @Test
testRegisterForNtnSignalStrengthChangedWithFeatureFlagEnabled()2591     public void testRegisterForNtnSignalStrengthChangedWithFeatureFlagEnabled() {
2592         Semaphore semaphore = new Semaphore(0);
2593         final NtnSignalStrength[] signalStrength = new NtnSignalStrength[1];
2594         INtnSignalStrengthCallback callback =
2595                 new INtnSignalStrengthCallback.Stub() {
2596                     @Override
2597                     public void onNtnSignalStrengthChanged(NtnSignalStrength ntnSignalStrength) {
2598                         logd("onNtnSignalStrengthChanged: ntnSignalStrength="
2599                                 + ntnSignalStrength);
2600                         try {
2601                             signalStrength[0] = ntnSignalStrength;
2602                             semaphore.release();
2603                         } catch (Exception ex) {
2604                             loge("onNtnSignalStrengthChanged: Got exception in releasing "
2605                                     + "semaphore, ex=" + ex);
2606                         }
2607                     }
2608                 };
2609 
2610         verifyRegisterForNtnSignalStrengthChanged(SUB_ID, callback,
2611                 SATELLITE_RESULT_INVALID_TELEPHONY_STATE);
2612 
2613         setUpResponseForRequestIsSatelliteSupported(false,
2614                 SATELLITE_RESULT_SUCCESS);
2615         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
2616         verifyRegisterForNtnSignalStrengthChanged(SUB_ID, callback,
2617                 SATELLITE_RESULT_NOT_SUPPORTED);
2618 
2619         @NtnSignalStrength.NtnSignalStrengthLevel int expectedLevel = NTN_SIGNAL_STRENGTH_NONE;
2620         verifyRequestNtnSignalStrength(expectedLevel, SATELLITE_RESULT_NOT_SUPPORTED);
2621 
2622         resetSatelliteControllerUT();
2623         setUpResponseForRequestNtnSignalStrength(expectedLevel, SATELLITE_RESULT_SUCCESS);
2624         provisionSatelliteService();
2625         verifyRegisterForNtnSignalStrengthChanged(SUB_ID, callback,
2626                 SATELLITE_RESULT_SUCCESS);
2627         verifyRequestNtnSignalStrength(expectedLevel, SATELLITE_RESULT_SUCCESS);
2628         processAllMessages();
2629         assertTrue(waitForForEvents(
2630                 semaphore, 1, "testRegisterForNtnSignalStrengthChanged"));
2631         assertEquals(expectedLevel, signalStrength[0].getLevel());
2632 
2633         expectedLevel = NTN_SIGNAL_STRENGTH_GOOD;
2634         sendNtnSignalStrengthChangedEvent(expectedLevel, null);
2635         processAllMessages();
2636         assertTrue(waitForForEvents(
2637                 semaphore, 1, "testRegisterForNtnSignalStrengthChanged"));
2638         assertEquals(expectedLevel, signalStrength[0].getLevel());
2639         verifyRequestNtnSignalStrength(NTN_SIGNAL_STRENGTH_GOOD, SATELLITE_RESULT_SUCCESS);
2640 
2641         expectedLevel = NTN_SIGNAL_STRENGTH_POOR;
2642         sendNtnSignalStrengthChangedEvent(expectedLevel, null);
2643         processAllMessages();
2644         assertTrue(waitForForEvents(
2645                 semaphore, 1, "testRegisterForNtnSignalStrengthChanged"));
2646         assertEquals(expectedLevel, signalStrength[0].getLevel());
2647         verifyRequestNtnSignalStrength(NTN_SIGNAL_STRENGTH_POOR, SATELLITE_RESULT_SUCCESS);
2648 
2649         mSatelliteControllerUT.unregisterForNtnSignalStrengthChanged(callback);
2650         sendNtnSignalStrengthChangedEvent(NTN_SIGNAL_STRENGTH_GREAT, null);
2651         processAllMessages();
2652         assertFalse(waitForForEvents(
2653                 semaphore, 1, "testRegisterForNtnSignalStrengthChanged"));
2654         /* Even if all listeners are unregistered, the cache is updated with the latest value when a
2655          new value event occurs. */
2656         verifyRequestNtnSignalStrength(NTN_SIGNAL_STRENGTH_GREAT, SATELLITE_RESULT_SUCCESS);
2657     }
2658 
2659     @Test
testSendingNtnSignalStrengthWithFeatureEnabled()2660     public void testSendingNtnSignalStrengthWithFeatureEnabled() {
2661         int expectedResult = SATELLITE_RESULT_SUCCESS;
2662         // startSendingNtnSignalStrength() is requested when screen on event comes.
2663         reset(mMockSatelliteModemInterface);
2664         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2665         provisionSatelliteService();
2666         setUpResponseForStartSendingNtnSignalStrength(expectedResult);
2667 
2668         // but it is ignored because satellite is disabled
2669         setUpResponseForRequestIsSatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
2670         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
2671         sendCmdStartSendingNtnSignalStrengthChangedEvent(true);
2672         processAllMessages();
2673         verify(mMockSatelliteModemInterface, never())
2674                 .startSendingNtnSignalStrength(any(Message.class));
2675 
2676         // after satellite is enabled, startSendingNtnSignalStrength() is requested normally
2677         resetSatelliteControllerUT();
2678         reset(mMockSatelliteModemInterface);
2679         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2680         provisionSatelliteService();
2681         setUpResponseForStartSendingNtnSignalStrength(expectedResult);
2682         setUpResponseForRequestIsSatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
2683         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
2684         processAllMessages();
2685         sendCmdStartSendingNtnSignalStrengthChangedEvent(true);
2686         processAllMessages();
2687         verify(mMockSatelliteModemInterface, times(1))
2688                 .startSendingNtnSignalStrength(any(Message.class));
2689 
2690         // requested again but ignored as expected and current state are matched.
2691         setUpResponseForStartSendingNtnSignalStrength(expectedResult);
2692         sendCmdStartSendingNtnSignalStrengthChangedEvent(true);
2693         processAllMessages();
2694         verify(mMockSatelliteModemInterface, times(1))
2695                 .startSendingNtnSignalStrength(any(Message.class));
2696 
2697         // stopSendingNtnSignalStrength() is requested when screen off event comes.
2698         reset(mMockSatelliteModemInterface);
2699         setUpResponseForRequestIsSatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
2700         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
2701         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2702         setUpResponseForStopSendingNtnSignalStrength(expectedResult);
2703         sendCmdStartSendingNtnSignalStrengthChangedEvent(false);
2704         processAllMessages();
2705         verify(mMockSatelliteModemInterface, times(1))
2706                 .stopSendingNtnSignalStrength(any(Message.class));
2707 
2708         // requested again but ignored as expected and current state are matched.
2709         setUpResponseForStopSendingNtnSignalStrength(expectedResult);
2710         sendCmdStartSendingNtnSignalStrengthChangedEvent(false);
2711         processAllMessages();
2712         verify(mMockSatelliteModemInterface, times(1))
2713                 .stopSendingNtnSignalStrength(any(Message.class));
2714 
2715         // startSendingNtnSignalStrength() is requested but received fail from the service.
2716         reset(mMockSatelliteModemInterface);
2717         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2718         setUpResponseForStartSendingNtnSignalStrength(SATELLITE_RESULT_INVALID_MODEM_STATE);
2719         sendCmdStartSendingNtnSignalStrengthChangedEvent(true);
2720         processAllMessages();
2721         verify(mMockSatelliteModemInterface, times(1))
2722                 .startSendingNtnSignalStrength(any(Message.class));
2723 
2724         /* stopSendingNtnSignalStrength() is ignored because startSendingNtnSignalStrength has
2725            failed thus current state is stopSendingNtnSignalStrength */
2726         reset(mMockSatelliteModemInterface);
2727         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2728         setUpResponseForStopSendingNtnSignalStrength(SATELLITE_RESULT_NO_RESOURCES);
2729         sendCmdStartSendingNtnSignalStrengthChangedEvent(false);
2730         processAllMessages();
2731         verify(mMockSatelliteModemInterface, never())
2732                 .stopSendingNtnSignalStrength(any(Message.class));
2733 
2734         // startSendingNtnSignalStrength() is requested and modem state is changed
2735         reset(mMockSatelliteModemInterface);
2736         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2737         setUpResponseForStartSendingNtnSignalStrength(SATELLITE_RESULT_SUCCESS);
2738         sendCmdStartSendingNtnSignalStrengthChangedEvent(true);
2739         processAllMessages();
2740         verify(mMockSatelliteModemInterface, times(1))
2741                 .startSendingNtnSignalStrength(any(Message.class));
2742 
2743         // stopSendingNtnSignalStrength() is failed as modem returns error
2744         reset(mMockSatelliteModemInterface);
2745         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2746         setUpResponseForStopSendingNtnSignalStrength(SATELLITE_RESULT_NO_RESOURCES);
2747         sendCmdStartSendingNtnSignalStrengthChangedEvent(false);
2748         processAllMessages();
2749         verify(mMockSatelliteModemInterface, times(1))
2750                 .stopSendingNtnSignalStrength(any(Message.class));
2751 
2752         // request stopSendingNtnSignalStrength() again and returns success
2753         reset(mMockSatelliteModemInterface);
2754         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2755         setUpResponseForStopSendingNtnSignalStrength(SATELLITE_RESULT_SUCCESS);
2756         sendCmdStartSendingNtnSignalStrengthChangedEvent(false);
2757         processAllMessages();
2758         verify(mMockSatelliteModemInterface, times(1))
2759                 .stopSendingNtnSignalStrength(any(Message.class));
2760     }
2761 
2762     @Test
testIsSatelliteSupportedViaCarrier()2763     public void testIsSatelliteSupportedViaCarrier() {
2764         assertFalse(mSatelliteControllerUT.isSatelliteSupportedViaCarrier());
2765 
2766         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
2767         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
2768                 : mCarrierConfigChangedListenerList) {
2769             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
2770                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
2771             );
2772         }
2773         processAllMessages();
2774         assertTrue(mSatelliteControllerUT.isSatelliteSupportedViaCarrier());
2775     }
2776 
2777     @Test
testCarrierEnabledSatelliteConnectionHysteresisTime()2778     public void testCarrierEnabledSatelliteConnectionHysteresisTime() throws Exception {
2779         when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
2780         when(mServiceState2.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
2781         mCarrierConfigBundle.putInt(KEY_SATELLITE_CONNECTION_HYSTERESIS_SEC_INT, 1 * 60);
2782         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
2783         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
2784                 : mCarrierConfigChangedListenerList) {
2785             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
2786                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
2787             );
2788         }
2789         doReturn(mSignalStrength).when(mPhone).getSignalStrength();
2790         doReturn(mSignalStrength).when(mPhone2).getSignalStrength();
2791         List<CellSignalStrength> cellSignalStrengthList = new ArrayList<>();
2792         cellSignalStrengthList.add(mCellSignalStrength);
2793         doReturn(cellSignalStrengthList).when(mSignalStrength).getCellSignalStrengths();
2794         processAllMessages();
2795         mSatelliteControllerUT.elapsedRealtime = 0;
2796         assertFalse(mSatelliteControllerUT
2797                         .isSatelliteConnectedViaCarrierWithinHysteresisTime().first);
2798         assertFalse(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone));
2799         assertFalse(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone2));
2800 
2801         when(mServiceState.isUsingNonTerrestrialNetwork()).thenReturn(false);
2802         when(mServiceState2.isUsingNonTerrestrialNetwork()).thenReturn(false);
2803         sendServiceStateChangedEvent();
2804         processAllMessages();
2805         assertFalse(mSatelliteControllerUT
2806                         .isSatelliteConnectedViaCarrierWithinHysteresisTime().first);
2807         assertFalse(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone));
2808         assertFalse(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone2));
2809         verify(mPhone, times(1)).notifyCarrierRoamingNtnModeChanged(eq(false));
2810         verify(mPhone2, times(1)).notifyCarrierRoamingNtnModeChanged(eq(false));
2811         clearInvocations(mPhone);
2812         clearInvocations(mPhone2);
2813 
2814         // Last satellite connected time of Phone2 should be 0
2815         when(mServiceState2.isUsingNonTerrestrialNetwork()).thenReturn(true);
2816         sendServiceStateChangedEvent();
2817         processAllMessages();
2818         // 2 minutes later and hysteresis timeout is 1 minute
2819         mSatelliteControllerUT.elapsedRealtime = 2 * 60 * 1000;
2820         // But Phone2 is connected to NTN right now
2821         assertTrue(mSatelliteControllerUT
2822                        .isSatelliteConnectedViaCarrierWithinHysteresisTime().first);
2823         assertFalse(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone));
2824         assertTrue(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone2));
2825         verify(mPhone, times(0)).notifyCarrierRoamingNtnModeChanged(eq(false));
2826         verify(mPhone2, times(1)).notifyCarrierRoamingNtnModeChanged(eq(true));
2827         clearInvocations(mPhone);
2828         clearInvocations(mPhone2);
2829 
2830         // Last satellite disconnected time of Phone2 should be 2 * 60 * 1000
2831         when(mServiceState2.isUsingNonTerrestrialNetwork()).thenReturn(false);
2832         sendServiceStateChangedEvent();
2833         processAllMessages();
2834         // Current time (2) - last disconnected time (2) < hysteresis timeout (1)
2835         assertTrue(mSatelliteControllerUT
2836                        .isSatelliteConnectedViaCarrierWithinHysteresisTime().first);
2837         assertFalse(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone));
2838         assertTrue(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone2));
2839         verify(mPhone, times(0)).notifyCarrierRoamingNtnModeChanged(eq(false));
2840         verify(mPhone2, times(0)).notifyCarrierRoamingNtnModeChanged(anyBoolean());
2841         clearInvocations(mPhone);
2842         clearInvocations(mPhone2);
2843 
2844         // Current time (4) - last disconnected time (2) > hysteresis timeout (1)
2845         mSatelliteControllerUT.elapsedRealtime = 4 * 60 * 1000;
2846         moveTimeForward(2 * 60 * 1000);
2847         processAllMessages();
2848         assertFalse(mSatelliteControllerUT
2849                         .isSatelliteConnectedViaCarrierWithinHysteresisTime().first);
2850         assertFalse(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone));
2851         assertFalse(mSatelliteControllerUT.isInSatelliteModeForCarrierRoaming(mPhone2));
2852         verify(mPhone, times(0)).notifyCarrierRoamingNtnModeChanged(eq(false));
2853         verify(mPhone2, times(1)).notifyCarrierRoamingNtnModeChanged(eq(false));
2854     }
2855 
2856     @Test
testRegisterForSatelliteCapabilitiesChangedWithFeatureFlagEnabled()2857     public void testRegisterForSatelliteCapabilitiesChangedWithFeatureFlagEnabled() {
2858         Semaphore semaphore = new Semaphore(0);
2859         final SatelliteCapabilities[] satelliteCapabilities = new SatelliteCapabilities[1];
2860         ISatelliteCapabilitiesCallback callback =
2861                 new ISatelliteCapabilitiesCallback.Stub() {
2862                     @Override
2863                     public void onSatelliteCapabilitiesChanged(SatelliteCapabilities capabilities) {
2864                         logd("onSatelliteCapabilitiesChanged: " + capabilities);
2865                         try {
2866                             satelliteCapabilities[0] = capabilities;
2867                             semaphore.release();
2868                         } catch (Exception ex) {
2869                             loge("onSatelliteCapabilitiesChanged: Got exception in releasing "
2870                                     + "semaphore, ex=" + ex);
2871                         }
2872                     }
2873                 };
2874 
2875         int errorCode = mSatelliteControllerUT.registerForCapabilitiesChanged(callback);
2876         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE, errorCode);
2877 
2878         setUpResponseForRequestIsSatelliteSupported(false,
2879                 SATELLITE_RESULT_SUCCESS);
2880         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
2881         errorCode = mSatelliteControllerUT.registerForCapabilitiesChanged(callback);
2882         assertEquals(SATELLITE_RESULT_NOT_SUPPORTED, errorCode);
2883 
2884         resetSatelliteControllerUT();
2885         provisionSatelliteService();
2886         errorCode = mSatelliteControllerUT.registerForCapabilitiesChanged(callback);
2887         assertEquals(SATELLITE_RESULT_SUCCESS, errorCode);
2888         SatelliteCapabilities expectedCapabilities = mSatelliteCapabilities;
2889         sendSatelliteCapabilitiesChangedEvent(expectedCapabilities, null);
2890         processAllMessages();
2891         assertTrue(waitForForEvents(
2892                 semaphore, 1, "testRegisterForSatelliteCapabilitiesChanged"));
2893         assertTrue(expectedCapabilities.equals(satelliteCapabilities[0]));
2894 
2895         expectedCapabilities = mEmptySatelliteCapabilities;
2896         sendSatelliteCapabilitiesChangedEvent(expectedCapabilities, null);
2897         processAllMessages();
2898         assertTrue(waitForForEvents(
2899                 semaphore, 1, "testRegisterForSatelliteCapabilitiesChanged"));
2900         assertTrue(expectedCapabilities.equals(satelliteCapabilities[0]));
2901 
2902         mSatelliteControllerUT.unregisterForCapabilitiesChanged(callback);
2903         expectedCapabilities = mSatelliteCapabilities;
2904         sendSatelliteCapabilitiesChangedEvent(expectedCapabilities, null);
2905         processAllMessages();
2906         assertTrue(waitForForEvents(
2907                 semaphore, 0, "testRegisterForSatelliteCapabilitiesChanged"));
2908     }
2909 
2910     @Test
testSatelliteCommunicationRestrictionForEntitlement()2911     public void testSatelliteCommunicationRestrictionForEntitlement() throws Exception {
2912         logd("testSatelliteCommunicationRestrictionForEntitlement");
2913 
2914         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
2915                 true);
2916         SparseBooleanArray satelliteEnabledPerCarrier = new SparseBooleanArray();
2917         replaceInstance(SatelliteController.class, "mSatelliteEntitlementStatusPerCarrier",
2918                 mSatelliteControllerUT, satelliteEnabledPerCarrier);
2919 
2920         mIIntegerConsumerResults.clear();
2921         reset(mMockSatelliteModemInterface);
2922         setUpResponseForRequestSetSatelliteEnabledForCarrier(true, SATELLITE_RESULT_SUCCESS);
2923         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2924         Map<Integer, Set<Integer>> satelliteAttachRestrictionForCarrierArray = new HashMap<>();
2925         satelliteAttachRestrictionForCarrierArray.put(SUB_ID, new HashSet<>());
2926         satelliteAttachRestrictionForCarrierArray.get(SUB_ID).add(
2927                 SATELLITE_COMMUNICATION_RESTRICTION_REASON_ENTITLEMENT);
2928         replaceInstance(SatelliteController.class, "mSatelliteAttachRestrictionForCarrierArray",
2929                 mSatelliteControllerUT, satelliteAttachRestrictionForCarrierArray);
2930 
2931         // Verify call the requestSetSatelliteEnabledForCarrier to enable the satellite when
2932         // satellite service is enabled by entitlement server.
2933         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, true, new ArrayList<>(),
2934                 new ArrayList<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(),
2935                 new HashMap<>(), mIIntegerConsumer);
2936         processAllMessages();
2937 
2938         assertTrue(waitForIIntegerConsumerResult(1));
2939         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2940         verify(mPhone, times(1))
2941                 .setSatelliteEnabledForCarrier(anyInt(), eq(true), any(Message.class));
2942 
2943         // Verify call the requestSetSatelliteEnabledForCarrier to disable the satellite when
2944         // satellite service is disabled by entitlement server.
2945         mIIntegerConsumerResults.clear();
2946         reset(mMockSatelliteModemInterface);
2947         Map<Integer, Boolean> enabledForCarrierArrayPerSub = new HashMap<>();
2948         enabledForCarrierArrayPerSub.put(SUB_ID, true);
2949         replaceInstance(SatelliteController.class, "mIsSatelliteAttachEnabledForCarrierArrayPerSub",
2950                 mSatelliteControllerUT, enabledForCarrierArrayPerSub);
2951         doReturn(mIsSatelliteServiceSupported)
2952                 .when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
2953         setUpResponseForRequestSetSatelliteEnabledForCarrier(false, SATELLITE_RESULT_SUCCESS);
2954         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false, new ArrayList<>(),
2955                 new ArrayList<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(),
2956                 new HashMap<>(), mIIntegerConsumer);
2957         processAllMessages();
2958 
2959         assertTrue(waitForIIntegerConsumerResult(1));
2960         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
2961         verify(mPhone, times(1))
2962                 .setSatelliteEnabledForCarrier(anyInt(), eq(false), any(Message.class));
2963     }
2964 
2965     @Test
testPassSatellitePlmnToModemAfterUpdateSatelliteEntitlementStatus()2966     public void testPassSatellitePlmnToModemAfterUpdateSatelliteEntitlementStatus()
2967             throws Exception {
2968         logd("testPassSatellitePlmnToModemAfterUpdateSatelliteEntitlementStatus");
2969 
2970         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
2971                 mSatelliteControllerUT, new SparseArray<>());
2972         List<String> overlayConfigPlmnList = new ArrayList<>();
2973         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
2974                 mSatelliteControllerUT, overlayConfigPlmnList);
2975         mCarrierConfigBundle.putBoolean(
2976                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
2977         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
2978                 true);
2979 
2980         // If the entitlement plmn list, the carrier plmn list, the overlay config plmn list and
2981         // the barred plmn list are empty, verify not passing to the modem.
2982         reset(mMockSatelliteModemInterface);
2983         List<String> entitlementPlmnList = new ArrayList<>();
2984         List<String> barredPlmnList = new ArrayList<>();
2985         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
2986                 entitlementPlmnList, barredPlmnList, new HashMap<>(), new HashMap<>(),
2987                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
2988         verify(mMockSatelliteModemInterface, never()).requestSatelliteEnabled(
2989                 any(SatelliteModemEnableRequestAttributes.class), any(Message.class));
2990 
2991         // If the entitlement plmn list and the overlay config plmn list are available and the
2992         // carrier plmn list and the barred plmn list are empty, verify passing to the modem.
2993         reset(mMockSatelliteModemInterface);
2994         entitlementPlmnList = Arrays.stream(new String[]{"00101", "00102", "00103"}).toList();
2995         List<String> mergedPlmnList = entitlementPlmnList;
2996         overlayConfigPlmnList =
2997                 Arrays.stream(new String[]{"00101", "00102", "00104"}).toList();
2998         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
2999                 mSatelliteControllerUT, overlayConfigPlmnList);
3000         verifyPassingToModemAfterQueryCompleted(entitlementPlmnList, mergedPlmnList,
3001                 overlayConfigPlmnList, barredPlmnList);
3002 
3003         // If the entitlement plmn list, the overlay config plmn list and the carrier plmn list
3004         // are available and the barred plmn list is empty, verify passing to the modem.
3005         reset(mMockSatelliteModemInterface);
3006         reset(mPhone);
3007         Map<Integer, Map<String, Set<Integer>>>
3008                 satelliteServicesSupportedByCarriers = new HashMap<>();
3009         List<String> carrierConfigPlmnList = Arrays.stream(new String[]{"00105", "00106"}).toList();
3010         Map<String, Set<Integer>> plmnAndService = new HashMap<>();
3011         plmnAndService.put(carrierConfigPlmnList.get(0), new HashSet<>(Arrays.asList(3, 5)));
3012         plmnAndService.put(carrierConfigPlmnList.get(1), new HashSet<>(Arrays.asList(3)));
3013         satelliteServicesSupportedByCarriers.put(SUB_ID, plmnAndService);
3014         replaceInstance(SatelliteController.class,
3015                 "mSatelliteServicesSupportedByCarriersFromConfig",
3016                 mSatelliteControllerUT, satelliteServicesSupportedByCarriers);
3017         verifyPassingToModemAfterQueryCompleted(entitlementPlmnList, mergedPlmnList,
3018                 overlayConfigPlmnList, barredPlmnList);
3019 
3020         // If the entitlement plmn list is empty and the overlay config plmn list and the carrier
3021         // plmn list are available, verify passing to the modem.
3022         reset(mMockSatelliteModemInterface);
3023         reset(mPhone);
3024         entitlementPlmnList = new ArrayList<>();
3025         mergedPlmnList = carrierConfigPlmnList;
3026         verifyPassingToModemAfterQueryCompleted(entitlementPlmnList, mergedPlmnList,
3027                 overlayConfigPlmnList, barredPlmnList);
3028 
3029 
3030         // If the entitlement plmn list is empty and the overlay config plmn list, the carrier
3031         // plmn list and the barred plmn list are available, verify passing to the modem.
3032         reset(mMockSatelliteModemInterface);
3033         reset(mPhone);
3034         barredPlmnList = Arrays.stream(new String[]{"00105", "00107"}).toList();
3035         verifyPassingToModemAfterQueryCompleted(entitlementPlmnList, mergedPlmnList,
3036                 overlayConfigPlmnList, barredPlmnList);
3037 
3038         // If the entitlement plmn list is null and the overlay config plmn list and the carrier
3039         // plmn list are available, verify passing to the modem.
3040         reset(mMockSatelliteModemInterface);
3041         reset(mPhone);
3042         entitlementPlmnList = null;
3043         mergedPlmnList = carrierConfigPlmnList;
3044         verifyPassingToModemAfterQueryCompleted(entitlementPlmnList, mergedPlmnList,
3045                 overlayConfigPlmnList, barredPlmnList);
3046 
3047         // If the entitlement plmn list is invalid, verify not passing to the modem.
3048         reset(mMockSatelliteModemInterface);
3049         reset(mPhone);
3050         entitlementPlmnList = Arrays.stream(new String[]{"00101", "00102", ""}).toList();
3051         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
3052                 entitlementPlmnList, barredPlmnList, new HashMap<>(), new HashMap<>(),
3053                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
3054         verify(mMockSatelliteModemInterface, never()).requestSatelliteEnabled(
3055                 any(SatelliteModemEnableRequestAttributes.class), any(Message.class));
3056 
3057         // If the entitlement plmn list is invalid, verify not passing to the modem.
3058         reset(mMockSatelliteModemInterface);
3059         reset(mPhone);
3060         entitlementPlmnList = Arrays.stream(new String[]{"00101", "00102", "123456789"}).toList();
3061         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
3062                 entitlementPlmnList, barredPlmnList, new HashMap<>(), new HashMap<>(),
3063                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
3064         verify(mMockSatelliteModemInterface, never()).requestSatelliteEnabled(
3065                 any(SatelliteModemEnableRequestAttributes.class), any(Message.class));
3066 
3067         // If the entitlement plmn list is invalid, verify not passing to the modem.
3068         reset(mMockSatelliteModemInterface);
3069         reset(mPhone);
3070         entitlementPlmnList = Arrays.stream(new String[]{"00101", "00102", "12"}).toList();
3071         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
3072                 entitlementPlmnList, barredPlmnList, new HashMap<>(), new HashMap<>(),
3073                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
3074         verify(mMockSatelliteModemInterface, never()).requestSatelliteEnabled(
3075                 any(SatelliteModemEnableRequestAttributes.class), any(Message.class));
3076 
3077         // If the entitlement plmn list is invalid, verify not passing to the modem.
3078         reset(mMockSatelliteModemInterface);
3079         reset(mPhone);
3080         entitlementPlmnList = Arrays.stream(new String[]{"00101", "00102", "1234"}).toList();
3081         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
3082                 entitlementPlmnList, barredPlmnList, new HashMap<>(), new HashMap<>(),
3083                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
3084         verify(mMockSatelliteModemInterface, never()).requestSatelliteEnabled(
3085                 any(SatelliteModemEnableRequestAttributes.class), any(Message.class));
3086     }
3087 
verifyPassingToModemAfterQueryCompleted(List<String> entitlementPlmnList, List<String> mergedPlmnList, List<String> overlayConfigPlmnList, List<String> barredPlmnList)3088     private void verifyPassingToModemAfterQueryCompleted(List<String> entitlementPlmnList,
3089             List<String> mergedPlmnList, List<String> overlayConfigPlmnList,
3090             List<String> barredPlmnList) {
3091         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
3092                 entitlementPlmnList, barredPlmnList, new HashMap<>(), new HashMap<>(),
3093                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
3094 
3095         List<String> plmnListPerCarrier = mSatelliteControllerUT.getSatellitePlmnsForCarrier(
3096                 SUB_ID);
3097         List<String> allSatellitePlmnList = SatelliteServiceUtils.mergeStrLists(
3098                 plmnListPerCarrier, overlayConfigPlmnList, barredPlmnList);
3099 
3100         assertEquals(mergedPlmnList, plmnListPerCarrier);
3101         if (overlayConfigPlmnList.isEmpty()) {
3102             assertEquals(plmnListPerCarrier, allSatellitePlmnList);
3103         }
3104         verify(mPhone, times(1)).setSatellitePlmn(anyInt(),
3105                 eq(plmnListPerCarrier), anyList(), any(Message.class));
3106     }
3107 
setConfigData(List<String> plmnList)3108     private void setConfigData(List<String> plmnList) {
3109         doReturn(plmnList).when(mMockConfig).getAllSatellitePlmnsForCarrier(anyInt());
3110         doReturn(mMockConfig).when(mMockConfigParser).getConfig();
3111 
3112         Map<String, List<Integer>> servicePerPlmn = new HashMap<>();
3113         List<List<Integer>> serviceLists = Arrays.asList(
3114                 Arrays.asList(1),
3115                 Arrays.asList(3),
3116                 Arrays.asList(5)
3117         );
3118         for (int i = 0; i < plmnList.size(); i++) {
3119             servicePerPlmn.put(plmnList.get(i), serviceLists.get(i));
3120         }
3121         doReturn(servicePerPlmn).when(mMockConfig).getSupportedSatelliteServices(anyInt());
3122         doReturn(mMockConfig).when(mMockConfigParser).getConfig();
3123     }
3124 
3125     @Test
testUpdateSupportedSatelliteServices()3126     public void testUpdateSupportedSatelliteServices() throws Exception {
3127         logd("testUpdateSupportedSatelliteServices");
3128         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
3129                 mSatelliteControllerUT, new SparseArray<>());
3130         replaceInstance(SatelliteController.class,
3131                 "mSatelliteServicesSupportedByCarriersFromConfig",
3132                 mSatelliteControllerUT, new HashMap<>());
3133         List<Integer> servicesPerPlmn;
3134 
3135         // verify whether an empty list is returned with conditions below
3136         // the config data plmn list : empty
3137         // the carrier config plmn list : empty
3138         setConfigData(new ArrayList<>());
3139         setCarrierConfigDataPlmnList(new ArrayList<>());
3140         invokeCarrierConfigChanged();
3141         servicesPerPlmn = mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(
3142                 SUB_ID, "31016");
3143         assertEquals(new ArrayList<>(), servicesPerPlmn);
3144 
3145         // Verify whether the carrier config plmn list is returned with conditions below
3146         // the config data plmn list : empty
3147         // the carrier config plmn list : exist with services {{2}, {1, 3}, {2}}
3148         setConfigData(new ArrayList<>());
3149         setCarrierConfigDataPlmnList(Arrays.asList("00101", "00102", "00104"));
3150         invokeCarrierConfigChanged();
3151         servicesPerPlmn = mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(
3152                 SUB_ID, "00101");
3153         assertEquals(Arrays.asList(2).stream().sorted().toList(),
3154                 servicesPerPlmn.stream().sorted().toList());
3155         servicesPerPlmn = mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(
3156                 SUB_ID, "00102");
3157         assertEquals(Arrays.asList(1, 3).stream().sorted().toList(),
3158                 servicesPerPlmn.stream().sorted().toList());
3159         servicesPerPlmn = mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(
3160                 SUB_ID, "00104");
3161         assertEquals(Arrays.asList(2).stream().sorted().toList(),
3162                 servicesPerPlmn.stream().sorted().toList());
3163 
3164         // Verify whether the carrier config plmn list is returned with conditions below
3165         // the config data plmn list : exist with services {{1}, {3}, {5}}
3166         // the carrier config plmn list : exist with services {{2}, {1, 3}, {2}}
3167         setConfigData(Arrays.asList("00101", "00102", "31024"));
3168         setCarrierConfigDataPlmnList(Arrays.asList("00101", "00102", "00104"));
3169         invokeCarrierConfigChanged();
3170         servicesPerPlmn = mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(
3171                 SUB_ID, "00101");
3172         assertEquals(Arrays.asList(1).stream().sorted().toList(),
3173                 servicesPerPlmn.stream().sorted().toList());
3174         servicesPerPlmn = mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(
3175                 SUB_ID, "00102");
3176         assertEquals(Arrays.asList(3).stream().sorted().toList(),
3177                 servicesPerPlmn.stream().sorted().toList());
3178         servicesPerPlmn = mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(
3179                 SUB_ID, "00104");
3180         assertEquals(new ArrayList<>(), servicesPerPlmn.stream().sorted().toList());
3181         servicesPerPlmn = mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(
3182                 SUB_ID, "31024");
3183         assertEquals(Arrays.asList(5).stream().sorted().toList(),
3184                 servicesPerPlmn.stream().sorted().toList());
3185     }
setEntitlementPlmnList(List<String> plmnList)3186     private void setEntitlementPlmnList(List<String> plmnList) throws Exception {
3187         SparseArray<List<String>> entitlementPlmnListPerCarrier = new SparseArray<>();
3188         if (!plmnList.isEmpty()) {
3189             entitlementPlmnListPerCarrier.clear();
3190             entitlementPlmnListPerCarrier.put(SUB_ID, plmnList);
3191         }
3192         replaceInstance(SatelliteController.class, "mEntitlementPlmnListPerCarrier",
3193                 mSatelliteControllerUT, entitlementPlmnListPerCarrier);
3194     }
3195 
setEntitlementPlmnList(SatelliteController targetClass, int subId, List<String> plmnList)3196     private void setEntitlementPlmnList(SatelliteController targetClass, int subId,
3197             List<String> plmnList) throws Exception {
3198         SparseArray<List<String>> entitlementPlmnListPerCarrier = new SparseArray<>();
3199         if (!plmnList.isEmpty()) {
3200             entitlementPlmnListPerCarrier.clear();
3201             entitlementPlmnListPerCarrier.put(subId, plmnList);
3202         }
3203         replaceInstance(SatelliteController.class, "mEntitlementPlmnListPerCarrier",
3204                 targetClass, entitlementPlmnListPerCarrier);
3205     }
3206 
setConfigDataPlmnList(List<String> plmnList)3207     private void setConfigDataPlmnList(List<String> plmnList) {
3208         doReturn(plmnList).when(mMockConfig).getAllSatellitePlmnsForCarrier(anyInt());
3209         doReturn(mMockConfig).when(mMockConfigParser).getConfig();
3210     }
3211 
setCarrierConfigDataPlmnList(List<String> plmnList)3212     private void setCarrierConfigDataPlmnList(List<String> plmnList) {
3213         if (!plmnList.isEmpty()) {
3214             mCarrierConfigBundle.putBoolean(
3215                     CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
3216                     true);
3217             PersistableBundle carrierSupportedSatelliteServicesPerProvider =
3218                     new PersistableBundle();
3219             List<String> carrierConfigPlmnList = plmnList;
3220             carrierSupportedSatelliteServicesPerProvider.putIntArray(
3221                     carrierConfigPlmnList.get(0), new int[]{2});
3222             carrierSupportedSatelliteServicesPerProvider.putIntArray(
3223                     carrierConfigPlmnList.get(1), new int[]{1, 3});
3224             carrierSupportedSatelliteServicesPerProvider.putIntArray(
3225                     carrierConfigPlmnList.get(2), new int[]{2});
3226             mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
3227                             .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
3228                     carrierSupportedSatelliteServicesPerProvider);
3229         } else {
3230             mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
3231                             .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
3232                     new PersistableBundle());
3233         }
3234     }
3235 
invokeCarrierConfigChanged()3236     private void invokeCarrierConfigChanged() {
3237         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3238                 : mCarrierConfigChangedListenerList) {
3239             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3240                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3241             );
3242         }
3243         processAllMessages();
3244     }
3245 
3246     @Test
testUpdatePlmnListPerCarrier()3247     public void testUpdatePlmnListPerCarrier() throws Exception {
3248         logd("testUpdatePlmnListPerCarrier");
3249 
3250         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
3251                 mSatelliteControllerUT, new SparseArray<>());
3252         mCarrierConfigBundle.putBoolean(
3253                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
3254         List<String> plmnListPerCarrier;
3255 
3256         // verify whether an empty list is returned with conditions below
3257         // the entitlement plmn list : empty
3258         // the config data plmn list : empty
3259         // the carrier config plmn list : empty
3260         setEntitlementPlmnList(new ArrayList<>());
3261         setConfigDataPlmnList(new ArrayList<>());
3262         setCarrierConfigDataPlmnList(new ArrayList<>());
3263         invokeCarrierConfigChanged();
3264         plmnListPerCarrier = mSatelliteControllerUT.getSatellitePlmnsForCarrier(SUB_ID);
3265         assertEquals(new ArrayList<>(), plmnListPerCarrier.stream().sorted().toList());
3266 
3267         // Verify whether the carrier config plmn list is returned with conditions below
3268         // the entitlement plmn list : empty
3269         // the config data plmn list : empty
3270         // the carrier config plmn list : exist
3271         setEntitlementPlmnList(new ArrayList<>());
3272         setConfigDataPlmnList(new ArrayList<>());
3273         setCarrierConfigDataPlmnList(Arrays.asList("00101", "00102", "00104"));
3274         invokeCarrierConfigChanged();
3275         plmnListPerCarrier = mSatelliteControllerUT.getSatellitePlmnsForCarrier(SUB_ID);
3276         assertEquals(Arrays.asList("00101", "00102", "00104").stream().sorted().toList(),
3277                 plmnListPerCarrier.stream().sorted().toList());
3278 
3279         // Verify whether config data plmn list is returned with conditions below
3280         // the entitlement plmn list : empty
3281         // the config data plmn list : exist
3282         // the carrier config plmn list : exist
3283         setEntitlementPlmnList(new ArrayList<>());
3284         setConfigDataPlmnList(Arrays.asList("11111", "22222", "33333"));
3285         setCarrierConfigDataPlmnList(Arrays.asList("00101", "00102", "00104"));
3286         invokeCarrierConfigChanged();
3287         plmnListPerCarrier = mSatelliteControllerUT.getSatellitePlmnsForCarrier(SUB_ID);
3288         assertEquals(Arrays.asList("11111", "22222", "33333").stream().sorted().toList(),
3289                 plmnListPerCarrier.stream().sorted().toList());
3290 
3291         // Verify whether the entitlement plmn list is returned with conditions below
3292         // the entitlement plmn list : exist
3293         // the config data plmn list : exist
3294         // the carrier config plmn list : exist
3295         setEntitlementPlmnList(Arrays.asList("99090", "88080", "77070"));
3296         setConfigDataPlmnList(Arrays.asList("11111", "22222", "33333"));
3297         setCarrierConfigDataPlmnList(Arrays.asList("00101", "00102", "00104"));
3298         invokeCarrierConfigChanged();
3299         plmnListPerCarrier = mSatelliteControllerUT.getSatellitePlmnsForCarrier(SUB_ID);
3300         assertEquals(Arrays.asList("99090", "88080", "77070").stream().sorted().toList(),
3301                 plmnListPerCarrier.stream().sorted().toList());
3302     }
3303 
3304     @Test
testEntitlementStatus()3305     public void testEntitlementStatus() throws Exception {
3306         logd("testEntitlementStatus");
3307         SparseBooleanArray satelliteEnabledPerCarrier = new SparseBooleanArray();
3308         replaceInstance(SatelliteController.class, "mSatelliteEntitlementStatusPerCarrier",
3309                 mSatelliteControllerUT, satelliteEnabledPerCarrier);
3310 
3311         // Change SUB_ID's EntitlementStatus to true
3312         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, true, new ArrayList<>(),
3313                 new ArrayList<>(), new HashMap<>(), new HashMap<>(),
3314                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
3315 
3316         assertEquals(true, satelliteEnabledPerCarrier.get(SUB_ID));
3317         assertEquals(false, satelliteEnabledPerCarrier.get(SUB_ID1));
3318 
3319         // Change SUB_ID1's EntitlementStatus to true
3320         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID1, true, new ArrayList<>(),
3321                 new ArrayList<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(),
3322                 new HashMap<>(), mIIntegerConsumer);
3323 
3324         assertEquals(true, satelliteEnabledPerCarrier.get(SUB_ID));
3325         assertEquals(true, satelliteEnabledPerCarrier.get(SUB_ID1));
3326 
3327         // Change SUB_ID's EntitlementStatus to false
3328         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false, new ArrayList<>(),
3329                 new ArrayList<>(), new HashMap<>(), new HashMap<>(), new HashMap<>(),
3330                 new HashMap<>(), mIIntegerConsumer);
3331 
3332         assertEquals(false, satelliteEnabledPerCarrier.get(SUB_ID));
3333         assertEquals(true, satelliteEnabledPerCarrier.get(SUB_ID1));
3334     }
3335 
3336     @Test
testUpdateRestrictReasonForEntitlementPerCarrier()3337     public void testUpdateRestrictReasonForEntitlementPerCarrier() throws Exception {
3338         logd("testUpdateRestrictReasonForEntitlementPerCarrier");
3339 
3340         // Verify that the entitlement restriction reason is added before the entitlement query,
3341         // When the Satellite entitlement status value read from DB is disabled.
3342         doReturn("").when(mContext).getOpPackageName();
3343         doReturn("").when(mContext).getAttributionTag();
3344         doReturn("0").when(mMockSubscriptionManagerService).getSubscriptionProperty(anyInt(),
3345                 eq(SATELLITE_ENTITLEMENT_STATUS), anyString(), anyString());
3346         doReturn(new ArrayList<>()).when(
3347                 mMockSubscriptionManagerService).getSatelliteEntitlementPlmnList(anyInt());
3348         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
3349                 true);
3350         mCarrierConfigBundle.putBoolean(
3351                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
3352         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3353                 : mCarrierConfigChangedListenerList) {
3354             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3355                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3356             );
3357         }
3358         processAllMessages();
3359         Set<Integer> restrictionSet =
3360                 mSatelliteControllerUT.getAttachRestrictionReasonsForCarrier(SUB_ID);
3361         assertEquals(1, restrictionSet.size());
3362         assertTrue(restrictionSet.contains(SATELLITE_COMMUNICATION_RESTRICTION_REASON_ENTITLEMENT));
3363     }
3364 
3365     @Test
testVerifyEntitlementDataInPersistenceMemory()3366     public void testVerifyEntitlementDataInPersistenceMemory() throws Exception {
3367         // When the entitlement data was not set, verify for not null and empty data sets.
3368         assertEquals(new ArrayList<>(),
3369                 mMockSubscriptionManagerService.getSatelliteEntitlementBarredPlmnList(anyInt()));
3370         assertEquals(new HashMap<>(),
3371                 mMockSubscriptionManagerService.getSatelliteEntitlementDataPlanForPlmns(anyInt()));
3372         assertEquals(new HashMap<>(),
3373                 mMockSubscriptionManagerService.getSatelliteEntitlementPlmnServiceTypeMap(
3374                         anyInt()));
3375         assertEquals(new HashMap<>(),
3376                 mMockSubscriptionManagerService.getSatelliteEntitlementPlmnDataServicePolicy(
3377                         anyInt()));
3378         assertEquals(new HashMap<>(),
3379                 mMockSubscriptionManagerService.getSatelliteEntitlementPlmnVoiceServicePolicy(
3380                         anyInt()));
3381     }
3382 
3383     @Test
testUpdateEntitlementPlmnListPerCarrier()3384     public void testUpdateEntitlementPlmnListPerCarrier() throws Exception {
3385         logd("testUpdateEntitlementPlmnListPerCarrier");
3386 
3387         // If the Satellite entitlement plmn list read from the DB is empty list and carrier
3388         // config plmn list also is empty , check whether an empty list is returned when calling
3389         // getSatellitePlmnsForCarrier before the entitlement query.
3390         doReturn(new ArrayList<>()).when(
3391                 mMockSubscriptionManagerService).getSatelliteEntitlementPlmnList(anyInt());
3392         replaceInstance(SatelliteController.class, "mEntitlementPlmnListPerCarrier",
3393                 mSatelliteControllerUT, new SparseArray<>());
3394         replaceInstance(SatelliteController.class,
3395                 "mSatelliteServicesSupportedByCarriersFromConfig",
3396                 mSatelliteControllerUT, new HashMap<>());
3397         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
3398                 true);
3399         mCarrierConfigBundle.putBoolean(
3400                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
3401         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3402                 : mCarrierConfigChangedListenerList) {
3403             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3404                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3405             );
3406         }
3407         processAllMessages();
3408 
3409         assertEquals(new ArrayList<>(), mSatelliteControllerUT.getSatellitePlmnsForCarrier(SUB_ID));
3410 
3411         // If the Satellite entitlement plmn list read from the DB is valid and carrier config
3412         // plmn list is empty, check whether valid entitlement plmn list is returned
3413         // when calling getSatellitePlmnsForCarrier before the entitlement query.
3414         replaceInstance(SatelliteController.class, "mEntitlementPlmnListPerCarrier",
3415                 mSatelliteControllerUT, new SparseArray<>());
3416         List<String> expectedSatelliteEntitlementPlmnList = Arrays.asList("123456,12560");
3417         doReturn(expectedSatelliteEntitlementPlmnList).when(
3418                 mMockSubscriptionManagerService).getSatelliteEntitlementPlmnList(anyInt());
3419         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3420                 : mCarrierConfigChangedListenerList) {
3421             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3422                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3423             );
3424         }
3425         processAllMessages();
3426 
3427         assertEquals(expectedSatelliteEntitlementPlmnList,
3428                 mSatelliteControllerUT.getSatellitePlmnsForCarrier(SUB_ID));
3429 
3430         // If the Satellite entitlement plmn list read from the DB is valid and carrier config
3431         // plmn list is valid, check whether valid entitlement plmn list is returned when
3432         // calling getSatellitePlmnsForCarrier before the entitlement query.
3433         replaceInstance(SatelliteController.class, "mEntitlementPlmnListPerCarrier",
3434                 mSatelliteControllerUT, new SparseArray<>());
3435         PersistableBundle carrierSupportedSatelliteServicesPerProvider = new PersistableBundle();
3436         List<String> carrierConfigPlmnList = Arrays.asList("00102", "00103", "00105");
3437         carrierSupportedSatelliteServicesPerProvider.putIntArray(
3438                 carrierConfigPlmnList.get(0), new int[]{2});
3439         carrierSupportedSatelliteServicesPerProvider.putIntArray(
3440                 carrierConfigPlmnList.get(1), new int[]{1, 3});
3441         carrierSupportedSatelliteServicesPerProvider.putIntArray(
3442                 carrierConfigPlmnList.get(2), new int[]{2});
3443         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
3444                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
3445                 carrierSupportedSatelliteServicesPerProvider);
3446         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3447                 : mCarrierConfigChangedListenerList) {
3448             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3449                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3450             );
3451         }
3452         processAllMessages();
3453 
3454         assertEquals(expectedSatelliteEntitlementPlmnList,
3455                 mSatelliteControllerUT.getSatellitePlmnsForCarrier(SUB_ID));
3456 
3457         // If the Satellite entitlement plmn list read from the DB is empty and carrier config
3458         // plmn list is valid, check whether valid carrier config plmn list is returned when
3459         // calling getSatellitePlmnsForCarrier before the entitlement query.
3460         replaceInstance(SatelliteController.class, "mEntitlementPlmnListPerCarrier",
3461                 mSatelliteControllerUT, new SparseArray<>());
3462         doReturn(new ArrayList<>()).when(
3463                 mMockSubscriptionManagerService).getSatelliteEntitlementPlmnList(anyInt());
3464         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3465                 : mCarrierConfigChangedListenerList) {
3466             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3467                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3468             );
3469         }
3470         processAllMessages();
3471 
3472         assertEquals(carrierConfigPlmnList.stream().sorted().toList(),
3473                 mSatelliteControllerUT.getSatellitePlmnsForCarrier(
3474                         SUB_ID).stream().sorted().toList());
3475     }
3476 
3477     @Test
testHandleEventServiceStateChanged()3478     public void testHandleEventServiceStateChanged() {
3479         mContextFixture.putBooleanResource(
3480             R.bool.config_satellite_should_notify_availability, true);
3481         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
3482         mCarrierConfigBundle.putInt(KEY_CARRIER_ROAMING_NTN_CONNECT_TYPE_INT,
3483                 CARRIER_ROAMING_NTN_CONNECT_AUTOMATIC);
3484         invokeCarrierConfigChanged();
3485 
3486         // Do nothing when the satellite is not connected
3487         doReturn(false).when(mServiceState).isUsingNonTerrestrialNetwork();
3488         sendServiceStateChangedEvent();
3489         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3490         processAllMessages();
3491         assertFalse(mSharedPreferences.getBoolean(SATELLITE_SYSTEM_NOTIFICATION_DONE_KEY, false));
3492         verify(mMockNotificationManager, never()).notifyAsUser(anyString(), anyInt(), any(), any());
3493 
3494         // Check sending a system notification when the satellite is connected
3495         doReturn(true).when(mServiceState).isUsingNonTerrestrialNetwork();
3496         sendServiceStateChangedEvent();
3497         processAllMessages();
3498         verify(mMockNotificationManager, times(1)).notifyAsUser(anyString(), anyInt(), any(),
3499                 any());
3500         // Just by showing notification we do not update the pref file , only once user interact
3501         // only we will update the pref value to true.
3502         assertFalse(mSharedPreferences.getBoolean(SATELLITE_SYSTEM_NOTIFICATION_DONE_KEY, false));
3503 
3504         // Check don't display again after displayed already a system notification.
3505         sendServiceStateChangedEvent();
3506         processAllMessages();
3507         verify(mMockNotificationManager, times(2)).notifyAsUser(anyString(), anyInt(), any(),
3508                 any());
3509     }
3510 
3511     @Test
testRequestSatelliteEnabled_timeout()3512     public void testRequestSatelliteEnabled_timeout() {
3513         mIsSatelliteEnabledSemaphore.drainPermits();
3514         mIIntegerConsumerResults.clear();
3515         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3516         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3517         setProvisionedState(true);
3518         processAllMessages();
3519         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
3520 
3521         // Successfully disable satellite
3522         mIIntegerConsumerResults.clear();
3523         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
3524         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
3525         processAllMessages();
3526         assertTrue(waitForIIntegerConsumerResult(1));
3527         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
3528         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
3529 
3530         // Time out to enable satellite
3531         ArgumentCaptor<SatelliteModemEnableRequestAttributes> enableSatelliteRequest =
3532                 ArgumentCaptor.forClass(SatelliteModemEnableRequestAttributes.class);
3533         ArgumentCaptor<Message> enableSatelliteResponse = ArgumentCaptor.forClass(Message.class);
3534         mIIntegerConsumerResults.clear();
3535         setUpNoResponseForRequestSatelliteEnabled(true, false, false);
3536         clearInvocations(mMockSatelliteModemInterface);
3537         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
3538         processAllMessages();
3539         assertFalse(waitForIIntegerConsumerResult(1));
3540         verify(mMockSatelliteModemInterface).requestSatelliteEnabled(
3541                 enableSatelliteRequest.capture(),
3542                 enableSatelliteResponse.capture());
3543         SatelliteModemEnableRequestAttributes request = enableSatelliteRequest.getValue();
3544         assertTrue(request.isEnabled());
3545         assertFalse(request.isForDemoMode());
3546         assertFalse(request.isForEmergencyMode());
3547 
3548         clearInvocations(mMockSatelliteModemInterface);
3549         moveTimeForward(TEST_WAIT_FOR_SATELLITE_ENABLING_RESPONSE_TIMEOUT_MILLIS);
3550         processAllMessages();
3551         assertTrue(waitForIIntegerConsumerResult(1));
3552         assertEquals(SATELLITE_RESULT_MODEM_TIMEOUT, (long) mIIntegerConsumerResults.get(0));
3553         verify(mMockSatelliteModemInterface).requestSatelliteEnabled(
3554                 any(SatelliteModemEnableRequestAttributes.class), any(Message.class));
3555         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
3556 
3557         // Send the response for the above request to enable satellite. SatelliteController should
3558         // ignore the event
3559         Message response = enableSatelliteResponse.getValue();
3560         AsyncResult.forMessage(response, null, null);
3561         response.sendToTarget();
3562         processAllMessages();
3563         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
3564 
3565         // Successfully enable satellite
3566         mIIntegerConsumerResults.clear();
3567         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
3568         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
3569         processAllMessages();
3570         assertTrue(waitForIIntegerConsumerResult(1));
3571         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
3572         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
3573 
3574         // Time out to disable satellite
3575         ArgumentCaptor<Message> disableSatelliteResponse = ArgumentCaptor.forClass(Message.class);
3576         mIIntegerConsumerResults.clear();
3577         clearInvocations(mMockSatelliteModemInterface);
3578         setUpNoResponseForRequestSatelliteEnabled(false, false, false);
3579         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
3580         processAllMessages();
3581         assertFalse(waitForIIntegerConsumerResult(1));
3582         verify(mMockSatelliteModemInterface).requestSatelliteEnabled(
3583                 any(SatelliteModemEnableRequestAttributes.class),
3584                 disableSatelliteResponse.capture());
3585 
3586         clearInvocations(mMockSatelliteModemInterface);
3587         moveTimeForward(TEST_WAIT_FOR_SATELLITE_ENABLING_RESPONSE_TIMEOUT_MILLIS);
3588         processAllMessages();
3589         assertTrue(waitForIIntegerConsumerResult(1));
3590         assertEquals(SATELLITE_RESULT_MODEM_TIMEOUT, (long) mIIntegerConsumerResults.get(0));
3591         verify(mMockSatelliteModemInterface, never()).requestSatelliteEnabled(
3592                 any(SatelliteModemEnableRequestAttributes.class), any(Message.class));
3593         // Satellite should state at enabled state since satellite disable request failed
3594         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
3595 
3596         // Send the response for the above request to disable satellite. SatelliteController should
3597         // ignore the event
3598         response = disableSatelliteResponse.getValue();
3599         AsyncResult.forMessage(response, null, null);
3600         response.sendToTarget();
3601         processAllMessages();
3602         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
3603     }
3604 
3605     @Test
testUpdateNtnSignalStrentghReportWithFeatureFlagEnabled()3606     public void testUpdateNtnSignalStrentghReportWithFeatureFlagEnabled() {
3607         mIsSatelliteEnabledSemaphore.drainPermits();
3608         mIIntegerConsumerResults.clear();
3609         resetSatelliteControllerUT();
3610         mSatelliteControllerUT.handleSatelliteAccessAllowedStateChanged(true);
3611 
3612         // Successfully provisioned
3613         reset(mMockSatelliteModemInterface);
3614         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
3615         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3616         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3617         setProvisionedState(true);
3618         setUpResponseForRequestIsSatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
3619         setProvisionedState(true);
3620         processAllMessages();
3621         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
3622 
3623         // startSendingNtnSignalStrength should be invoked when satellite is enabled
3624         mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled = false;
3625         mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled = false;
3626         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
3627         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
3628         processAllMessages();
3629         assertTrue(waitForIIntegerConsumerResult(1));
3630         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
3631         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
3632         assertTrue(mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled);
3633         assertTrue(mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled);
3634         assertEquals(
3635                 SATELLITE_MODE_ENABLED_TRUE, mSatelliteControllerUT.satelliteModeSettingValue);
3636         verify(mMockSatelliteModemInterface, times(1)).startSendingNtnSignalStrength(
3637                 any(Message.class));
3638 
3639         // Ignore request ntn signal strength for redundant enable request
3640         reset(mMockSatelliteModemInterface);
3641         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
3642         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
3643         processAllMessages();
3644         assertTrue(waitForIIntegerConsumerResult(1));
3645         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
3646         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
3647         verify(mMockSatelliteModemInterface, never()).startSendingNtnSignalStrength(
3648                 any(Message.class));
3649 
3650         // stopSendingNtnSignalStrength should be invoked when satellite is successfully off.
3651         mIIntegerConsumerResults.clear();
3652         reset(mMockSatelliteModemInterface);
3653         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
3654         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
3655         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
3656         processAllMessages();
3657         assertTrue(waitForIIntegerConsumerResult(1));
3658         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
3659         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
3660         verify(mMockSatelliteModemInterface, times(1)).stopSendingNtnSignalStrength(
3661                 any(Message.class));
3662 
3663         // Ignore redundant request for stop reporting ntn signal strength.
3664         mIIntegerConsumerResults.clear();
3665         reset(mMockSatelliteModemInterface);
3666         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
3667         mIIntegerConsumerResults.clear();
3668         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
3669         mSatelliteControllerUT.requestSatelliteEnabled(false, false, false, mIIntegerConsumer);
3670         processAllMessages();
3671         assertTrue(waitForIIntegerConsumerResult(1));
3672         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
3673         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
3674         verify(mMockSatelliteModemInterface, never()).stopSendingNtnSignalStrength(
3675                 any(Message.class));
3676 
3677         // startSendingNtnSignalStrength is invoked when satellite is enabled again.
3678         mIIntegerConsumerResults.clear();
3679         reset(mMockSatelliteModemInterface);
3680         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
3681         mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled = false;
3682         mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled = false;
3683         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
3684         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
3685         processAllMessages();
3686         assertTrue(waitForIIntegerConsumerResult(1));
3687         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
3688         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
3689         assertTrue(mSatelliteControllerUT.setSettingsKeyForSatelliteModeCalled);
3690         assertTrue(mSatelliteControllerUT.setSettingsKeyToAllowDeviceRotationCalled);
3691         assertEquals(
3692                 SATELLITE_MODE_ENABLED_TRUE, mSatelliteControllerUT.satelliteModeSettingValue);
3693         verify(mMockSatelliteModemInterface, times(1)).startSendingNtnSignalStrength(
3694                 any(Message.class));
3695     }
3696 
3697     @Test
testRegisterForSatelliteSupportedStateChanged_WithFeatureFlagEnabled()3698     public void testRegisterForSatelliteSupportedStateChanged_WithFeatureFlagEnabled() {
3699         Semaphore semaphore = new Semaphore(0);
3700         final boolean[] isSupported  = new boolean[1];
3701         IBooleanConsumer callback =
3702                 new IBooleanConsumer.Stub() {
3703                     @Override
3704                     public void accept(boolean supported) {
3705                         logd("onSatelliteSupportedStateChanged: supported=" + supported);
3706                         isSupported[0] = supported;
3707                         try {
3708                             semaphore.release();
3709                         } catch (Exception ex) {
3710                             loge("onSatelliteSupportedStateChanged: Got exception in releasing "
3711                                     + "semaphore, ex=" + ex);
3712                         }
3713                     }
3714                 };
3715 
3716         resetSatelliteControllerUT();
3717         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3718         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3719         int errorCode = mSatelliteControllerUT.registerForSatelliteSupportedStateChanged(callback);
3720         assertEquals(SATELLITE_RESULT_SUCCESS, errorCode);
3721 
3722         sendSatelliteSupportedStateChangedEvent(true, null);
3723         processAllMessages();
3724         // Verify redundant report is ignored
3725         assertFalse(waitForForEvents(
3726                 semaphore, 1, "testRegisterForSatelliteSupportedStateChanged"));
3727         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3728 
3729         // Verify updated state is reported
3730         sendSatelliteSupportedStateChangedEvent(false, null);
3731         processAllMessages();
3732         assertTrue(waitForForEvents(
3733                 semaphore, 1, "testRegisterForSatelliteSupportedStateChanged"));
3734         assertEquals(false, isSupported[0]);
3735         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
3736 
3737         // Verify redundant report is ignored
3738         sendSatelliteSupportedStateChangedEvent(false, null);
3739         processAllMessages();
3740         assertFalse(waitForForEvents(
3741                 semaphore, 1, "testRegisterForSatelliteSupportedStateChanged"));
3742         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
3743 
3744         // Verify updated state is reported
3745         sendSatelliteSupportedStateChangedEvent(true, null);
3746         processAllMessages();
3747         assertTrue(waitForForEvents(
3748                 semaphore, 1, "testRegisterForSatelliteSupportedStateChanged"));
3749         assertEquals(true, isSupported[0]);
3750         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3751 
3752         // Successfully enable satellite
3753         setProvisionedState(true);
3754         processAllMessages();
3755         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
3756         mIIntegerConsumerResults.clear();
3757         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
3758         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
3759         processAllMessages();
3760         assertTrue(waitForIIntegerConsumerResult(1));
3761         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
3762         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
3763 
3764         // Send satellite is not supported state from modem to disable satellite
3765         setUpResponseForRequestSatelliteEnabled(false, false, false, SATELLITE_RESULT_SUCCESS);
3766         sendSatelliteSupportedStateChangedEvent(false, null);
3767         processAllMessages();
3768         assertTrue(waitForForEvents(
3769                 semaphore, 1, "testRegisterForSatelliteSupportedStateChanged"));
3770         assertEquals(false, isSupported[0]);
3771 
3772         // It is needed to set satellite as support to check whether satellite is enabled or not
3773         sendSatelliteSupportedStateChangedEvent(true, null);
3774         processAllMessages();
3775         assertTrue(waitForForEvents(
3776                 semaphore, 1, "testRegisterForSatelliteSupportedStateChanged"));
3777         assertEquals(true, isSupported[0]);
3778         // Verify satellite was disabled
3779         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
3780 
3781         mSatelliteControllerUT.unregisterForSatelliteSupportedStateChanged(callback);
3782         sendSatelliteSupportedStateChangedEvent(true, null);
3783         processAllMessages();
3784         assertFalse(waitForForEvents(
3785                 semaphore, 1, "testRegisterForSatelliteSupportedStateChanged"));
3786     }
3787 
3788     @Test
testRegisterForSelectedNbIotSatelliteSubscriptionChanged_WithFeatureFlagEnabled()3789     public void testRegisterForSelectedNbIotSatelliteSubscriptionChanged_WithFeatureFlagEnabled() {
3790         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
3791 
3792         Semaphore semaphore = new Semaphore(0);
3793         final int[] selectedSubIds = new int[1];
3794         ISelectedNbIotSatelliteSubscriptionCallback callback =
3795                 new ISelectedNbIotSatelliteSubscriptionCallback.Stub() {
3796                     @Override
3797                     public void onSelectedNbIotSatelliteSubscriptionChanged(int selectedSubId) {
3798                         logd("onSelectedNbIotSatelliteSubscriptionChanged: selectedSubId="
3799                                 + selectedSubId);
3800                         try {
3801                             selectedSubIds[0] = selectedSubId;
3802                             semaphore.release();
3803                         } catch (Exception ex) {
3804                             loge("onSelectedNbIotSatelliteSubscriptionChanged: Got exception in "
3805                                     + "releasing semaphore, ex=" + ex);
3806                         }
3807                     }
3808                 };
3809 
3810         int errorCode = mSatelliteControllerUT.registerForSelectedNbIotSatelliteSubscriptionChanged(
3811                 callback);
3812         assertEquals(SATELLITE_RESULT_INVALID_TELEPHONY_STATE, errorCode);
3813 
3814         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
3815         verifySatelliteSupported(false, SATELLITE_RESULT_SUCCESS);
3816         errorCode = mSatelliteControllerUT.registerForSelectedNbIotSatelliteSubscriptionChanged(
3817                 callback);
3818         assertEquals(SATELLITE_RESULT_NOT_SUPPORTED, errorCode);
3819 
3820         // Register the callback and verify that the event is reported.
3821         resetSatelliteControllerUT();
3822         setUpResponseForRequestIsSatelliteProvisioned(true,SATELLITE_RESULT_SUCCESS);
3823         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3824         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
3825         errorCode = mSatelliteControllerUT.registerForSelectedNbIotSatelliteSubscriptionChanged(
3826                 callback);
3827         assertEquals(SATELLITE_RESULT_SUCCESS, errorCode);
3828         int expectedSubId = 1;
3829         sendSelectedNbIotSatelliteSubscriptionChangedEvent(expectedSubId, null);
3830         processAllMessages();
3831         assertTrue(waitForForEvents(
3832                 semaphore, 1, "testRegisterForSelectedNbIotSatelliteSubscriptionChanged"));
3833         assertEquals(expectedSubId, selectedSubIds[0]);
3834 
3835         // Unregister the callback and verify that the event is not reported.
3836         mSatelliteControllerUT.unregisterForSelectedNbIotSatelliteSubscriptionChanged(callback);
3837         sendSelectedNbIotSatelliteSubscriptionChangedEvent(2, null);
3838         processAllMessages();
3839         assertTrue(waitForForEvents(
3840                 semaphore, 0, "testRegisterForSelectedNbIotSatelliteSubscriptionChanged"));
3841     }
3842 
3843     @Test
testRegisterForSelectedNbIotSatelliteSubscriptionChanged_WithFeatureFlagDisabled()3844     public void testRegisterForSelectedNbIotSatelliteSubscriptionChanged_WithFeatureFlagDisabled() {
3845         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(false);
3846 
3847         Semaphore semaphore = new Semaphore(0);
3848         final int[] selectedSubIds = new int[1];
3849         ISelectedNbIotSatelliteSubscriptionCallback callback =
3850                 new ISelectedNbIotSatelliteSubscriptionCallback.Stub() {
3851                     @Override
3852                     public void onSelectedNbIotSatelliteSubscriptionChanged(int selectedSubId) {
3853                         logd("onSelectedNbIotSatelliteSubscriptionChanged: selectedSubId="
3854                                 + selectedSubId);
3855                         try {
3856                             selectedSubIds[0] = selectedSubId;
3857                             semaphore.release();
3858                         } catch (Exception ex) {
3859                             loge("onSelectedNbIotSatelliteSubscriptionChanged: Got exception in "
3860                                     + "releasing semaphore, ex=" + ex);
3861                         }
3862                     }
3863                 };
3864 
3865         int errorCode = mSatelliteControllerUT.registerForSelectedNbIotSatelliteSubscriptionChanged(
3866                 callback);
3867         assertEquals(SATELLITE_RESULT_REQUEST_NOT_SUPPORTED, errorCode);
3868 
3869         // Verify that the event is not reported.
3870         sendSelectedNbIotSatelliteSubscriptionChangedEvent(1, null);
3871         processAllMessages();
3872         assertTrue(waitForForEvents(
3873                 semaphore, 0, "testRegisterForSelectedNbIotSatelliteSubscriptionChanged"));
3874 
3875 
3876     }
3877 
3878     @Test
testIsSatelliteEmergencyMessagingSupportedViaCarrier()3879     public void testIsSatelliteEmergencyMessagingSupportedViaCarrier() {
3880         // Satellite attach is not supported
3881         assertFalse(mSatelliteControllerUT.isSatelliteEmergencyMessagingSupportedViaCarrier());
3882 
3883         // Trigger carrier config changed to enable satellite attach
3884         mCarrierConfigBundle.putBoolean(
3885                 CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
3886         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3887                 : mCarrierConfigChangedListenerList) {
3888             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3889                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3890             );
3891         }
3892         processAllMessages();
3893         assertFalse(mSatelliteControllerUT.isSatelliteEmergencyMessagingSupportedViaCarrier());
3894 
3895         // Trigger carrier config changed to enable satellite attach & emergency messaging
3896         mCarrierConfigBundle.putBoolean(
3897                 CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
3898         mCarrierConfigBundle.putBoolean(
3899                 CarrierConfigManager.KEY_EMERGENCY_MESSAGING_SUPPORTED_BOOL, true);
3900         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3901                 : mCarrierConfigChangedListenerList) {
3902             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3903                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3904             );
3905         }
3906         processAllMessages();
3907         assertTrue(mSatelliteControllerUT.isSatelliteEmergencyMessagingSupportedViaCarrier());
3908     }
3909 
3910     @Test
testGetCarrierEmergencyCallWaitForConnectionTimeoutMillis()3911     public void testGetCarrierEmergencyCallWaitForConnectionTimeoutMillis() {
3912         assertEquals(DEFAULT_CARRIER_EMERGENCY_CALL_WAIT_FOR_CONNECTION_TIMEOUT_MILLIS,
3913                 mSatelliteControllerUT.getCarrierEmergencyCallWaitForConnectionTimeoutMillis());
3914 
3915         // Trigger carrier config changed to enable satellite attach
3916         int timeoutMillisForCarrier1 = 1000;
3917         PersistableBundle carrierConfigBundle1 = new PersistableBundle();
3918         carrierConfigBundle1.putBoolean(
3919                 CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
3920         carrierConfigBundle1.putBoolean(
3921                 CarrierConfigManager.KEY_EMERGENCY_MESSAGING_SUPPORTED_BOOL, true);
3922         carrierConfigBundle1.putInt(
3923                 KEY_EMERGENCY_CALL_TO_SATELLITE_T911_HANDOVER_TIMEOUT_MILLIS_INT,
3924                 timeoutMillisForCarrier1);
3925         doReturn(carrierConfigBundle1)
3926                 .when(mCarrierConfigManager).getConfigForSubId(eq(SUB_ID), any());
3927 
3928         int timeoutMillisForCarrier2 = 2000;
3929         PersistableBundle carrierConfigBundle2 = new PersistableBundle();
3930         carrierConfigBundle2.putBoolean(
3931                 CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
3932         carrierConfigBundle2.putBoolean(
3933                 CarrierConfigManager.KEY_EMERGENCY_MESSAGING_SUPPORTED_BOOL, true);
3934         carrierConfigBundle2.putInt(
3935                 KEY_EMERGENCY_CALL_TO_SATELLITE_T911_HANDOVER_TIMEOUT_MILLIS_INT,
3936                 timeoutMillisForCarrier2);
3937         doReturn(carrierConfigBundle2)
3938                 .when(mCarrierConfigManager).getConfigForSubId(eq(SUB_ID1), any());
3939 
3940         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3941                 : mCarrierConfigChangedListenerList) {
3942             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3943                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3944             );
3945         }
3946         processAllMessages();
3947 
3948         // Both phones are not in satellite mode for carrier roaming, and thus the max timeout
3949         // duration - timeoutMillisForCarrier2 - is used
3950         assertEquals(timeoutMillisForCarrier2,
3951                 mSatelliteControllerUT.getCarrierEmergencyCallWaitForConnectionTimeoutMillis());
3952 
3953         // Phone 1 is in satellite mode for carrier roaming
3954         when(mServiceState.isUsingNonTerrestrialNetwork()).thenReturn(true);
3955         assertEquals(timeoutMillisForCarrier1,
3956                 mSatelliteControllerUT.getCarrierEmergencyCallWaitForConnectionTimeoutMillis());
3957 
3958         // Both phones are in satellite mode for carrier roaming. The timeout duration of the first
3959         // phone will be selected
3960         when(mServiceState2.isUsingNonTerrestrialNetwork()).thenReturn(true);
3961         assertEquals(timeoutMillisForCarrier1,
3962                 mSatelliteControllerUT.getCarrierEmergencyCallWaitForConnectionTimeoutMillis());
3963     }
3964 
3965     @Test
testIsCarrierRoamingNtnEligible()3966     public void testIsCarrierRoamingNtnEligible() {
3967         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(false);
3968         assertFalse(mSatelliteControllerUT.isCarrierRoamingNtnEligible(null));
3969 
3970         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
3971         when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
3972         when(mServiceState2.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
3973         when(mServiceState.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(null);
3974         when(mServiceState2.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(null);
3975         mSatelliteControllerUT.mIsApplicationSupportsP2P = true;
3976         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
3977         mCarrierConfigBundle.putInt(KEY_CARRIER_ROAMING_NTN_CONNECT_TYPE_INT, 1);
3978         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ROAMING_P2P_SMS_SUPPORTED_BOOL, true);
3979         int[] supportedServices2 = {2};
3980         int[] supportedServices3 = {1, 3};
3981         PersistableBundle carrierSupportedSatelliteServicesPerProvider = new PersistableBundle();
3982         carrierSupportedSatelliteServicesPerProvider.putIntArray(
3983                 "00102", supportedServices2);
3984         carrierSupportedSatelliteServicesPerProvider.putIntArray(
3985                 "00103", supportedServices3);
3986         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
3987                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
3988                 carrierSupportedSatelliteServicesPerProvider);
3989         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
3990                 : mCarrierConfigChangedListenerList) {
3991             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
3992                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
3993             );
3994         }
3995         mSatelliteControllerUT.setSatellitePhone(1);
3996         mSatelliteControllerUT.setSelectedSatelliteSubId(SUB_ID);
3997         mSatelliteControllerUT.isSatelliteProvisioned = true;
3998         mSatelliteControllerUT.setIsSatelliteAllowedState(true);
3999         processAllMessages();
4000 
4001         assertTrue(mSatelliteControllerUT.isCarrierRoamingNtnEligible(mPhone));
4002 
4003         when(mServiceState.getState()).thenReturn(ServiceState.STATE_IN_SERVICE);
4004         when(mServiceState2.getState()).thenReturn(ServiceState.STATE_IN_SERVICE);
4005         processAllMessages();
4006         assertFalse(mSatelliteControllerUT.isCarrierRoamingNtnEligible(mPhone));
4007 
4008         when(mServiceState.getState()).thenReturn(ServiceState.STATE_IN_SERVICE);
4009         when(mServiceState2.getState()).thenReturn(ServiceState.STATE_IN_SERVICE);
4010         mSatelliteControllerUT.overrideCarrierRoamingNtnEligibilityChanged(true, false);
4011         processAllMessages();
4012         assertTrue(mSatelliteControllerUT.isCarrierRoamingNtnEligible(mPhone));
4013     }
4014 
4015     @Test
testOverrideCarrierRoamingNtNEligibilityChange()4016     public void testOverrideCarrierRoamingNtNEligibilityChange() {
4017         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4018         mSatelliteControllerUT.overrideCarrierRoamingNtnEligibilityChanged(true, false);
4019         verify(mPhone, times(1)).notifyCarrierRoamingNtnEligibleStateChanged(eq(true));
4020         clearInvocations(mPhone);
4021 
4022         mSatelliteControllerUT.overrideCarrierRoamingNtnEligibilityChanged(false, false);
4023         verify(mPhone, times(1)).notifyCarrierRoamingNtnEligibleStateChanged(eq(false));
4024         clearInvocations(mPhone);
4025 
4026         mSatelliteControllerUT.overrideCarrierRoamingNtnEligibilityChanged(false, true);
4027         verify(mPhone, times(0)).notifyCarrierRoamingNtnEligibleStateChanged(eq(true));
4028         clearInvocations(mPhone);
4029     }
4030 
4031     @Test
testNotifyNtnEligibilityHysteresisTimedOut()4032     public void testNotifyNtnEligibilityHysteresisTimedOut() {
4033         mContextFixture.putBooleanResource(
4034             R.bool.config_satellite_should_notify_availability, true);
4035         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4036         when(mServiceState2.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
4037         when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
4038         when(mServiceState.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(null);
4039         when(mServiceState2.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(null);
4040         mSatelliteControllerUT.mIsApplicationSupportsP2P = true;
4041         mSatelliteControllerUT.setIsSatelliteSupported(true);
4042         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
4043         mCarrierConfigBundle.putInt(KEY_CARRIER_ROAMING_NTN_CONNECT_TYPE_INT,
4044             CARRIER_ROAMING_NTN_CONNECT_MANUAL);
4045         mCarrierConfigBundle.putInt(
4046                 KEY_CARRIER_SUPPORTED_SATELLITE_NOTIFICATION_HYSTERESIS_SEC_INT, 1 * 60);
4047         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ROAMING_P2P_SMS_SUPPORTED_BOOL, true);
4048         int[] supportedServices2 = {2};
4049         int[] supportedServices3 = {1, 3};
4050         PersistableBundle carrierSupportedSatelliteServicesPerProvider = new PersistableBundle();
4051         carrierSupportedSatelliteServicesPerProvider.putIntArray(
4052                 "00102", supportedServices2);
4053         carrierSupportedSatelliteServicesPerProvider.putIntArray(
4054                 "00103", supportedServices3);
4055         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
4056                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
4057                 carrierSupportedSatelliteServicesPerProvider);
4058         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
4059                 : mCarrierConfigChangedListenerList) {
4060             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
4061                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
4062             );
4063         }
4064         mSatelliteControllerUT.setSatellitePhone(1);
4065         mSatelliteControllerUT.setSelectedSatelliteSubId(SUB_ID);
4066         mSatelliteControllerUT.isSatelliteProvisioned = true;
4067         mSatelliteControllerUT.isSatelliteAllowedCallback = null;
4068         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
4069         mSatelliteControllerUT.setIsSatelliteAllowedState(true);
4070         processAllMessages();
4071         mSatelliteControllerUT.elapsedRealtime = 0;
4072         assertTrue(mSatelliteControllerUT.isCarrierRoamingNtnEligible(mPhone));
4073         verify(mPhone, times(0)).notifyCarrierRoamingNtnEligibleStateChanged(eq(true));
4074         verify(mPhone2, times(0)).notifyCarrierRoamingNtnEligibleStateChanged(anyBoolean());
4075         clearInvocations(mPhone);
4076 
4077         // 2 minutes later and hysteresis timeout is 1 minute
4078         mSatelliteControllerUT.elapsedRealtime = 2 * 60 * 1000;
4079         moveTimeForward(2 * 60 * 1000);
4080         mSatelliteControllerUT.selectedSatelliteSubId = SUB_ID1;
4081         processAllMessages();
4082         assertTrue(mSatelliteControllerUT.isCarrierRoamingNtnEligible(mPhone));
4083         verify(mPhone, times(1)).notifyCarrierRoamingNtnEligibleStateChanged(eq(true));
4084         verify(mPhone2, times(0)).notifyCarrierRoamingNtnEligibleStateChanged(anyBoolean());
4085         verify(mMockNotificationManager, times(1)).notifyAsUser(anyString(), anyInt(), any(),
4086                 any());
4087         clearInvocations(mPhone);
4088 
4089         when(mServiceState.getState()).thenReturn(ServiceState.STATE_IN_SERVICE);
4090         sendServiceStateChangedEvent();
4091         processAllMessages();
4092         assertFalse(mSatelliteControllerUT.isCarrierRoamingNtnEligible(mPhone));
4093         verify(mPhone, times(1)).notifyCarrierRoamingNtnEligibleStateChanged(eq(false));
4094         verify(mPhone2, times(0)).notifyCarrierRoamingNtnEligibleStateChanged(anyBoolean());
4095     }
4096 
4097     @Test
testNotifyCarrierRoamingNtnSignalStrengthChanged()4098     public void testNotifyCarrierRoamingNtnSignalStrengthChanged() {
4099         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4100 
4101         sendSignalStrengthChangedEvent(mPhone.getPhoneId());
4102         processAllMessages();
4103         ArgumentCaptor<NtnSignalStrength> captor = ArgumentCaptor.forClass(NtnSignalStrength.class);
4104         verify(mPhone, times(1)).notifyCarrierRoamingNtnSignalStrengthChanged(
4105                 captor.capture());
4106         NtnSignalStrength actualSignalStrength = captor.getValue();
4107         assertEquals(NTN_SIGNAL_STRENGTH_NONE, actualSignalStrength.getLevel());
4108         clearInvocations(mPhone);
4109 
4110         when(mSignalStrength.getLevel()).thenReturn(SignalStrength.SIGNAL_STRENGTH_GOOD);
4111         when(mPhone.getSignalStrength()).thenReturn(mSignalStrength);
4112         mCarrierConfigBundle.putInt(KEY_SATELLITE_CONNECTION_HYSTERESIS_SEC_INT, 1 * 60);
4113         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
4114         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
4115                 : mCarrierConfigChangedListenerList) {
4116             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
4117                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
4118             );
4119         }
4120         processAllMessages();
4121         when(mServiceState.isUsingNonTerrestrialNetwork()).thenReturn(true);
4122         when(mServiceState.getState()).thenReturn(ServiceState.STATE_IN_SERVICE);
4123         sendServiceStateChangedEvent();
4124         processAllMessages();
4125         captor = ArgumentCaptor.forClass(NtnSignalStrength.class);
4126         verify(mPhone, times(1)).notifyCarrierRoamingNtnSignalStrengthChanged(
4127                 captor.capture());
4128         actualSignalStrength = captor.getValue();
4129         assertEquals(NTN_SIGNAL_STRENGTH_GOOD, actualSignalStrength.getLevel());
4130         clearInvocations(mPhone);
4131     }
4132 
4133     @Test
testGetWwanIsInService()4134     public void testGetWwanIsInService() {
4135         when(mServiceState.getNetworkRegistrationInfoListForTransportType(
4136                 eq(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)))
4137                 .thenReturn(new ArrayList<>());
4138         assertFalse(mSatelliteControllerUT.getWwanIsInService(mServiceState));
4139 
4140         NetworkRegistrationInfo nri = new NetworkRegistrationInfo.Builder()
4141                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_HOME)
4142                 .build();
4143         when(mServiceState.getNetworkRegistrationInfoListForTransportType(
4144                 eq(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)))
4145                 .thenReturn(List.of(nri));
4146         assertTrue(mSatelliteControllerUT.getWwanIsInService(mServiceState));
4147 
4148         nri = new NetworkRegistrationInfo.Builder()
4149                 .setRegistrationState(NetworkRegistrationInfo.REGISTRATION_STATE_ROAMING)
4150                 .build();
4151         when(mServiceState.getNetworkRegistrationInfoListForTransportType(
4152                 eq(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)))
4153                 .thenReturn(List.of(nri));
4154         assertTrue(mSatelliteControllerUT.getWwanIsInService(mServiceState));
4155 
4156         nri = new NetworkRegistrationInfo.Builder().setRegistrationState(
4157                         NetworkRegistrationInfo.REGISTRATION_STATE_NOT_REGISTERED_OR_SEARCHING)
4158                 .build();
4159         when(mServiceState.getNetworkRegistrationInfoListForTransportType(
4160                 eq(AccessNetworkConstants.TRANSPORT_TYPE_WWAN)))
4161                 .thenReturn(List.of(nri));
4162         assertFalse(mSatelliteControllerUT.getWwanIsInService(mServiceState));
4163     }
4164 
4165     @Test
testRegistrationFailureCallback()4166     public void testRegistrationFailureCallback() {
4167         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4168         Semaphore semaphore = new Semaphore(0);
4169         final int[] resultErrorCode = new int[1];
4170         ISatelliteModemStateCallback callback = new ISatelliteModemStateCallback.Stub() {
4171             @Override
4172             public void onSatelliteModemStateChanged(int state) {
4173                 logd("onSatelliteModemStateChanged: state=" + state);
4174             }
4175 
4176             @Override
4177             public void onEmergencyModeChanged(boolean isEmergency) {
4178                 logd("onEmergencyModeChanged: emergency=" + isEmergency);
4179             }
4180 
4181             @Override
4182             public void onRegistrationFailure(int causeCode) {
4183                 logd("onRegistrationFailure: causeCode=" + causeCode);
4184                 resultErrorCode[0] = causeCode;
4185                 semaphore.release();
4186             }
4187 
4188             @Override
4189             public void onTerrestrialNetworkAvailableChanged(boolean isAvailable) {
4190                 logd("onTerrestrialNetworkAvailableChanged: isAvailable=" + isAvailable);
4191             }
4192         };
4193         resetSatelliteControllerUTToSupportedAndProvisionedState();
4194         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
4195 
4196         int RegisterErrorCode = mSatelliteControllerUT.registerForSatelliteModemStateChanged(
4197                 callback);
4198         assertEquals(SATELLITE_RESULT_SUCCESS, RegisterErrorCode);
4199         verify(mMockSatelliteSessionController).registerForSatelliteModemStateChanged(callback);
4200 
4201         int expectedErrorCode = 100;
4202         mIIntegerConsumerResults.clear();
4203         sendSatelliteRegistrationFailureEvent(100, null);
4204         processAllMessages();
4205         assertTrue(waitForForEvents(
4206                 semaphore, 1, "testRegistrationFailureCallback"));
4207         assertEquals(expectedErrorCode, resultErrorCode[0]);
4208     }
4209 
4210     @RequiresFlagsDisabled(FLAG_DEVICE_STATE_PROPERTY_MIGRATION)
4211     @Test
testDetermineIsFoldable_overlayConfigurationValues()4212     public void testDetermineIsFoldable_overlayConfigurationValues() {
4213         // isFoldable should return false with the base configuration.
4214         assertFalse(mSatelliteControllerUT.isFoldable(mContext,
4215                 mSatelliteControllerUT.getSupportedDeviceStates()));
4216 
4217         mContextFixture.putIntArrayResource(R.array.config_foldedDeviceStates, new int[2]);
4218         assertTrue(mSatelliteControllerUT.isFoldable(mContext,
4219                 mSatelliteControllerUT.getSupportedDeviceStates()));
4220     }
4221 
4222     @RequiresFlagsEnabled(FLAG_DEVICE_STATE_PROPERTY_MIGRATION)
4223     @Test
testDetermineIsFoldable_deviceStateManager()4224     public void testDetermineIsFoldable_deviceStateManager() {
4225         // isFoldable should return false with the base configuration.
4226         assertFalse(mSatelliteControllerUT.isFoldable(mContext,
4227                 mSatelliteControllerUT.getSupportedDeviceStates()));
4228 
4229         DeviceState foldedDeviceState = new DeviceState(new DeviceState.Configuration.Builder(
4230                 0 /* identifier */, "FOLDED")
4231                 .setSystemProperties(Set.of(PROPERTY_FOLDABLE_DISPLAY_CONFIGURATION_OUTER_PRIMARY))
4232                 .setPhysicalProperties(
4233                         Set.of(PROPERTY_FOLDABLE_HARDWARE_CONFIGURATION_FOLD_IN_CLOSED))
4234                 .build());
4235         DeviceState unfoldedDeviceState = new DeviceState(new DeviceState.Configuration.Builder(
4236                 1 /* identifier */, "UNFOLDED")
4237                 .setSystemProperties(Set.of(PROPERTY_FOLDABLE_DISPLAY_CONFIGURATION_INNER_PRIMARY))
4238                 .setPhysicalProperties(
4239                         Set.of(PROPERTY_FOLDABLE_HARDWARE_CONFIGURATION_FOLD_IN_OPEN))
4240                 .build());
4241         List<DeviceState> foldableDeviceStateList = List.of(foldedDeviceState, unfoldedDeviceState);
4242         assertTrue(mSatelliteControllerUT.isFoldable(mContext, foldableDeviceStateList));
4243     }
4244 
4245     @Test
testTerrestrialNetworkAvailableChangedCallback()4246     public void testTerrestrialNetworkAvailableChangedCallback() {
4247         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4248         Semaphore semaphore = new Semaphore(0);
4249         final int[] receivedScanResult = new int[1];
4250         ISatelliteModemStateCallback callback = new ISatelliteModemStateCallback.Stub() {
4251             @Override
4252             public void onSatelliteModemStateChanged(int state) {
4253                 logd("onSatelliteModemStateChanged: state=" + state);
4254             }
4255 
4256             @Override
4257             public void onEmergencyModeChanged(boolean isEmergency) {
4258                 logd("onEmergencyModeChanged: emergency=" + isEmergency);
4259             }
4260 
4261             @Override
4262             public void onRegistrationFailure(int causeCode) {
4263                 logd("onRegistrationFailure: causeCode=" + causeCode);
4264             }
4265 
4266             @Override
4267             public void onTerrestrialNetworkAvailableChanged(boolean isAvailable) {
4268                 logd("onTerrestrialNetworkAvailableChanged: isAvailable=" + isAvailable);
4269                 receivedScanResult[0] = isAvailable ? 1 : 0;
4270                 semaphore.release();
4271             }
4272         };
4273         resetSatelliteControllerUTToSupportedAndProvisionedState();
4274         mSatelliteControllerUT.setSatelliteSessionController(mMockSatelliteSessionController);
4275 
4276         int RegisterErrorCode = mSatelliteControllerUT.registerForSatelliteModemStateChanged(
4277                 callback);
4278         assertEquals(SATELLITE_RESULT_SUCCESS, RegisterErrorCode);
4279         verify(mMockSatelliteSessionController).registerForSatelliteModemStateChanged(callback);
4280 
4281         int expectedErrorCode = 1;
4282         mIIntegerConsumerResults.clear();
4283         sendTerrestrialNetworkAvailableChangedEvent(true, null);
4284         processAllMessages();
4285         assertTrue(waitForForEvents(
4286                 semaphore, 1, "testRegistrationFailureCallback"));
4287         assertEquals(expectedErrorCode, receivedScanResult[0]);
4288     }
4289 
4290     private boolean mProvisionState = false;
4291     private int mProvisionSateResultCode = -1;
4292     private Semaphore mProvisionSateSemaphore = new Semaphore(0);
4293     private ResultReceiver mProvisionSatelliteReceiver = new ResultReceiver(null) {
4294         @Override
4295         protected void onReceiveResult(int resultCode, Bundle resultData) {
4296             mProvisionSateResultCode = resultCode;
4297             logd("mProvisionSatelliteReceiver: resultCode=" + resultCode);
4298             if (resultCode == SATELLITE_RESULT_SUCCESS) {
4299                 if (resultData.containsKey(KEY_PROVISION_SATELLITE_TOKENS)) {
4300                     mProvisionState = resultData.getBoolean(KEY_PROVISION_SATELLITE_TOKENS);
4301                     logd("mProvisionSatelliteReceiver: mProvisionState=" + mProvisionState);
4302                 } else {
4303                     loge("KEY_PROVISION_SATELLITE_TOKENS does not exist.");
4304                     mProvisionState = false;
4305                 }
4306             } else {
4307                 mProvisionState = false;
4308             }
4309             try {
4310                 mProvisionSateSemaphore.release();
4311             } catch (Exception ex) {
4312                 loge("mProvisionSatelliteReceiver: Got exception in releasing semaphore, ex=" + ex);
4313             }
4314         }
4315     };
4316 
4317     private List<SatelliteSubscriberProvisionStatus>
4318             mRequestSatelliteSubscriberProvisionStatusResultList = new ArrayList<>();
4319     private int mRequestSatelliteSubscriberProvisionStatusResultCode = SATELLITE_RESULT_SUCCESS;
4320     private Semaphore mRequestSatelliteSubscriberProvisionStatusSemaphore = new Semaphore(0);
4321     private ResultReceiver mRequestSatelliteSubscriberProvisionStatusReceiver = new ResultReceiver(
4322             null) {
4323         @Override
4324         protected void onReceiveResult(int resultCode, Bundle resultData) {
4325             mRequestSatelliteSubscriberProvisionStatusResultCode = resultCode;
4326             logd("mRequestSatelliteSubscriberProvisionStatusReceiver: resultCode=" + resultCode);
4327             if (resultCode == SATELLITE_RESULT_SUCCESS) {
4328                 if (resultData.containsKey(KEY_REQUEST_PROVISION_SUBSCRIBER_ID_TOKEN)) {
4329                     mRequestSatelliteSubscriberProvisionStatusResultList =
4330                             resultData.getParcelableArrayList(
4331                                     KEY_REQUEST_PROVISION_SUBSCRIBER_ID_TOKEN,
4332                                     SatelliteSubscriberProvisionStatus.class);
4333                 } else {
4334                     loge("KEY_REQUEST_PROVISION_SUBSCRIBER_ID_TOKEN does not exist.");
4335                     mRequestSatelliteSubscriberProvisionStatusResultList = new ArrayList<>();
4336                 }
4337             } else {
4338                 mRequestSatelliteSubscriberProvisionStatusResultList = new ArrayList<>();
4339             }
4340             try {
4341                 mRequestSatelliteSubscriberProvisionStatusSemaphore.release();
4342             } catch (Exception ex) {
4343                 loge("mRequestSatelliteSubscriberProvisionStatusReceiver: Got exception in "
4344                         + "releasing "
4345                         + "semaphore, ex=" + ex);
4346             }
4347         }
4348     };
4349 
4350     @Test
testRequestSatelliteSubscriberProvisionStatus()4351     public void testRequestSatelliteSubscriberProvisionStatus() throws Exception {
4352         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4353         verifyRequestSatelliteSubscriberProvisionStatus();
4354     }
4355 
verifyRequestSatelliteSubscriberProvisionStatus()4356     private void verifyRequestSatelliteSubscriberProvisionStatus() throws Exception {
4357         setSatelliteSubscriberTesting(true);
4358         List<SatelliteSubscriberInfo> list = getExpectedSatelliteSubscriberInfoList();
4359         mCarrierConfigBundle.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
4360         mCarrierConfigBundle.putString(KEY_SATELLITE_NIDD_APN_NAME_STRING, mNiddApn);
4361         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ESOS_SUPPORTED_BOOL, true);
4362         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
4363                 : mCarrierConfigChangedListenerList) {
4364             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
4365                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
4366             );
4367         }
4368         moveTimeForward(TimeUnit.MINUTES.toMillis(1));
4369         processAllMessages();
4370 
4371         // Verify that calling requestSatelliteSubscriberProvisionStatus returns the expected
4372         // list of SatelliteSubscriberProvisionStatus.
4373         mSatelliteControllerUT.requestSatelliteSubscriberProvisionStatus(
4374                 mRequestSatelliteSubscriberProvisionStatusReceiver);
4375         moveTimeForward(TimeUnit.MINUTES.toMillis(1));
4376         processAllMessages();
4377         assertEquals(SATELLITE_RESULT_SUCCESS,
4378                 mRequestSatelliteSubscriberProvisionStatusResultCode);
4379         assertEquals(list.get(0), mRequestSatelliteSubscriberProvisionStatusResultList.get(
4380                 0).getSatelliteSubscriberInfo());
4381     }
4382 
4383     @Test
testProvisionSatellite()4384     public void testProvisionSatellite() throws Exception {
4385         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4386         verifyRequestSatelliteSubscriberProvisionStatus();
4387         List<SatelliteSubscriberInfo> inputList = getExpectedSatelliteSubscriberInfoList();
4388         verifyProvisionSatellite(inputList);
4389     }
4390 
verifyProvisionSatellite(List<SatelliteSubscriberInfo> inputList)4391     private void verifyProvisionSatellite(List<SatelliteSubscriberInfo> inputList) {
4392         doAnswer(invocation -> {
4393             Message message = (Message) invocation.getArguments()[1];
4394             AsyncResult.forMessage(message, null, new SatelliteException(SATELLITE_RESULT_SUCCESS));
4395             message.sendToTarget();
4396             return null;
4397         }).when(mMockSatelliteModemInterface).updateSatelliteSubscription(anyString(), any());
4398 
4399         mSatelliteControllerUT.provisionSatellite(inputList, mProvisionSatelliteReceiver);
4400         processAllMessages();
4401         assertEquals(SATELLITE_RESULT_SUCCESS, mProvisionSateResultCode);
4402         assertTrue(mProvisionState);
4403     }
4404 
4405     @Test
testRegisterForSatelliteSubscriptionProvisionStateChanged()4406     public void testRegisterForSatelliteSubscriptionProvisionStateChanged() throws Exception {
4407         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4408 
4409         Semaphore semaphore = new Semaphore(0);
4410         SatelliteSubscriberProvisionStatus[] resultArray =
4411                 new SatelliteSubscriberProvisionStatus[2];
4412         ISatelliteProvisionStateCallback callback = new ISatelliteProvisionStateCallback.Stub() {
4413             @Override
4414             public void onSatelliteProvisionStateChanged(boolean provisioned) {
4415                 logd("onSatelliteProvisionStateChanged: provisioned=" + provisioned);
4416             }
4417 
4418             @Override
4419             public void onSatelliteSubscriptionProvisionStateChanged(
4420                     List<SatelliteSubscriberProvisionStatus> satelliteSubscriberProvisionStatus) {
4421                 logd("onSatelliteSubscriptionProvisionStateChanged: "
4422                         + satelliteSubscriberProvisionStatus);
4423                 for (int i = 0; i < satelliteSubscriberProvisionStatus.size(); i++) {
4424                     resultArray[i] = satelliteSubscriberProvisionStatus.get(i);
4425                 }
4426                 try {
4427                     semaphore.release();
4428                 } catch (Exception ex) {
4429                     loge("onSatelliteSubscriptionProvisionStateChanged: Got exception in releasing "
4430                             + "semaphore, ex=" + ex);
4431                 }
4432             }
4433         };
4434 
4435         TestSubscriptionManager testSubscriptionManager = new TestSubscriptionManager();
4436         doAnswer(invocation -> {
4437             testSubscriptionManager.setIsSatelliteProvisionedForNonIpDatagram(
4438                     invocation.getArgument(0), invocation.getArgument(1));
4439             return null;
4440         }).when(mMockSubscriptionManagerService).setIsSatelliteProvisionedForNonIpDatagram(anyInt(),
4441                 anyBoolean());
4442         doAnswer(invocation -> testSubscriptionManager.isSatelliteProvisionedForNonIpDatagram(
4443                 invocation.getArgument(0))).when(
4444                 mMockSubscriptionManagerService).isSatelliteProvisionedForNonIpDatagram(anyInt());
4445 
4446         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
4447         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
4448         int errorCode = mSatelliteControllerUT.registerForSatelliteProvisionStateChanged(callback);
4449         processAllMessages();
4450         assertEquals(SATELLITE_RESULT_SUCCESS, errorCode);
4451 
4452         verifyRequestSatelliteSubscriberProvisionStatus();
4453 
4454         // Verify that onSatelliteSubscriptionProvisionStateChanged is called when requesting
4455         // provisioning for the first time.
4456         List<SatelliteSubscriberInfo> list = getExpectedSatelliteSubscriberInfoList();
4457         List<SatelliteSubscriberInfo> inputList = new ArrayList<>();
4458         inputList.add(list.get(0));
4459         verifyProvisionSatellite(inputList);
4460 
4461         verify(mMockSatelliteModemInterface, times(1)).updateSatelliteSubscription(anyString(),
4462                 any());
4463         assertTrue(waitForForEvents(
4464                 semaphore, 1, "testRegisterForSatelliteSubscriptionProvisionStateChanged"));
4465         assertTrue(resultArray[0].isProvisioned());
4466         assertEquals(mSubscriberId, resultArray[0].getSatelliteSubscriberInfo().getSubscriberId());
4467 
4468         // Request provisioning with SatelliteSubscriberInfo that has not been provisioned
4469         // before, and verify that onSatelliteSubscriptionProvisionStateChanged is called.
4470         inputList = new ArrayList<>();
4471         inputList.add(list.get(1));
4472         verifyProvisionSatellite(inputList);
4473 
4474         assertTrue(waitForForEvents(
4475                 semaphore, 1, "testRegisterForSatelliteSubscriptionProvisionStateChanged"));
4476         assertTrue(resultArray[1].isProvisioned());
4477         assertEquals(mSubscriberId2, resultArray[1].getSatelliteSubscriberInfo().getSubscriberId());
4478 
4479         // Request provisioning with the same SatelliteSubscriberInfo that was previously
4480         // requested, and verify that onSatelliteSubscriptionProvisionStateChanged is not called.
4481         verifyProvisionSatellite(inputList);
4482 
4483         assertFalse(waitForForEvents(
4484                 semaphore, 1, "testRegisterForSatelliteSubscriptionProvisionStateChanged"));
4485 
4486         // Request deprovision for subscriberID 2, verify that subscriberID 2 is set to
4487         // deprovision and that subscriberID 1 is set to provision.
4488         verifyDeprovisionSatellite(inputList);
4489         assertTrue(waitForForEvents(
4490                 semaphore, 1, "testRegisterForSatelliteSubscriptionProvisionStateChanged"));
4491         assertFalse(resultArray[1].isProvisioned());
4492         assertEquals(mSubscriberId2, resultArray[1].getSatelliteSubscriberInfo().getSubscriberId());
4493         assertTrue(resultArray[0].isProvisioned());
4494         assertEquals(mSubscriberId, resultArray[0].getSatelliteSubscriberInfo().getSubscriberId());
4495 
4496         // Request deprovision for subscriberID 1, verify that subscriberID 1 is set to deprovision.
4497         inputList = new ArrayList<>();
4498         inputList.add(list.get(0));
4499         verifyDeprovisionSatellite(inputList);
4500         assertTrue(waitForForEvents(
4501                 semaphore, 1, "testRegisterForSatelliteSubscriptionProvisionStateChanged"));
4502         assertFalse(resultArray[1].isProvisioned());
4503         assertEquals(mSubscriberId2, resultArray[1].getSatelliteSubscriberInfo().getSubscriberId());
4504         assertFalse(resultArray[0].isProvisioned());
4505         assertEquals(mSubscriberId, resultArray[0].getSatelliteSubscriberInfo().getSubscriberId());
4506 
4507         // Request provision for subscriberID 2, verify that subscriberID 2 is set to provision.
4508         inputList = new ArrayList<>();
4509         inputList.add(list.get(1));
4510         verifyProvisionSatellite(inputList);
4511 
4512         assertTrue(waitForForEvents(
4513                 semaphore, 1, "testRegisterForSatelliteSubscriptionProvisionStateChanged"));
4514         assertTrue(resultArray[1].isProvisioned());
4515         assertEquals(mSubscriberId2, resultArray[1].getSatelliteSubscriberInfo().getSubscriberId());
4516         assertFalse(resultArray[0].isProvisioned());
4517         assertEquals(mSubscriberId, resultArray[0].getSatelliteSubscriberInfo().getSubscriberId());
4518     }
4519 
4520     private boolean mDeprovisionDone = false;
4521     private int mDeprovisionSateResultCode = -1;
4522     private Semaphore mDeprovisionSateSemaphore = new Semaphore(0);
4523     private ResultReceiver mDeprovisionSatelliteReceiver = new ResultReceiver(null) {
4524         @Override
4525         protected void onReceiveResult(int resultCode, Bundle resultData) {
4526             mDeprovisionSateResultCode = resultCode;
4527             logd("DeprovisionSatelliteReceiver: resultCode=" + resultCode);
4528             if (resultCode == SATELLITE_RESULT_SUCCESS) {
4529                 if (resultData.containsKey(KEY_DEPROVISION_SATELLITE_TOKENS)) {
4530                     mDeprovisionDone = resultData.getBoolean(KEY_DEPROVISION_SATELLITE_TOKENS);
4531                     logd("DeprovisionSatelliteReceiver: deprovision=" + mDeprovisionDone);
4532                 } else {
4533                     loge("KEY_DEPROVISION_SATELLITE_TOKENS does not exist.");
4534                     mDeprovisionDone = false;
4535                 }
4536             } else {
4537                 mDeprovisionDone = false;
4538             }
4539             try {
4540                 mDeprovisionSateSemaphore.release();
4541             } catch (Exception ex) {
4542                 loge("DeprovisionSatelliteReceiver: Got exception in releasing semaphore " + ex);
4543             }
4544         }
4545     };
4546 
4547     @Test
testDeprovisionSatellite()4548     public void testDeprovisionSatellite() throws Exception {
4549         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4550         verifyRequestSatelliteSubscriberProvisionStatus();
4551         List<SatelliteSubscriberInfo> inputList = getExpectedSatelliteSubscriberInfoList();
4552         verifyProvisionSatellite(inputList);
4553         verifyDeprovisionSatellite(inputList);
4554     }
4555 
verifyDeprovisionSatellite(List<SatelliteSubscriberInfo> inputList)4556     private void verifyDeprovisionSatellite(List<SatelliteSubscriberInfo> inputList) {
4557         doAnswer(invocation -> {
4558             Message message = (Message) invocation.getArguments()[1];
4559             AsyncResult.forMessage(message, null, new SatelliteException(SATELLITE_RESULT_SUCCESS));
4560             message.sendToTarget();
4561             return null;
4562         }).when(mMockSatelliteModemInterface).updateSatelliteSubscription(anyString(), any());
4563 
4564         mSatelliteControllerUT.deprovisionSatellite(inputList, mDeprovisionSatelliteReceiver);
4565         processAllMessages();
4566         assertEquals(SATELLITE_RESULT_SUCCESS, mDeprovisionSateResultCode);
4567         assertTrue(mDeprovisionDone);
4568     }
4569 
setSatelliteSubscriberTesting(boolean sameCarrier)4570     private void setSatelliteSubscriberTesting(boolean sameCarrier) throws Exception {
4571         doReturn("123").when(mContext).getAttributionTag();
4572         final int carrierId_subID = 0;
4573         final int carrierId_subID1 = sameCarrier ? 0 : 1;
4574         SubscriptionInfo subscriptionInfo = new SubscriptionInfo.Builder()
4575                 .setId(SUB_ID).setIccId(mIccId).setSimSlotIndex(0).setOnlyNonTerrestrialNetwork(
4576                         false).setSatelliteESOSSupported(true).setCarrierId(
4577                             carrierId_subID).build();
4578         SubscriptionInfo subscriptionInfo2 = new SubscriptionInfo.Builder()
4579                 .setId(SUB_ID1).setIccId(mIccId2).setSimSlotIndex(1).setOnlyNonTerrestrialNetwork(
4580                         true).setSatelliteESOSSupported(false).setCarrierId(
4581                             carrierId_subID1).build();
4582         List<SubscriptionInfo> allSubInfos = new ArrayList<>();
4583         allSubInfos.add(subscriptionInfo);
4584         allSubInfos.add(subscriptionInfo2);
4585         testSubscriptionInfo = subscriptionInfo;
4586         testSubscriptionInfo2 = subscriptionInfo2;
4587         doReturn(allSubInfos).when(mMockSubscriptionManagerService).getAllSubInfoList(
4588                 anyString(), anyString());
4589         SubscriptionInfoInternal subInfoInternal =
4590                 new SubscriptionInfoInternal.Builder().setCarrierId(
4591                     carrierId_subID).setImsi(mImsi).setIccId(mIccId).build();
4592         SubscriptionInfoInternal subInfoInternal2 =
4593                 new SubscriptionInfoInternal.Builder().setCarrierId(
4594                     carrierId_subID1).setImsi(mImsi2).setIccId(mIccId2).build();
4595         doReturn(subscriptionInfo).when(mMockSubscriptionManagerService).getSubscriptionInfo(
4596                 eq(SUB_ID));
4597         doReturn(subscriptionInfo2).when(mMockSubscriptionManagerService).getSubscriptionInfo(
4598                 eq(SUB_ID1));
4599         Field field = SatelliteController.class.getDeclaredField("mInjectSubscriptionManager");
4600         field.setAccessible(true);
4601         field.set(mSatelliteControllerUT, mSubscriptionManager);
4602         doReturn(mMsisdn).when(mSubscriptionManager).getPhoneNumber(eq(SUB_ID));
4603         doReturn(mMsisdn2).when(mSubscriptionManager).getPhoneNumber(eq(SUB_ID1));
4604         Field provisionedSubscriberIdField = SatelliteController.class.getDeclaredField(
4605                 "mProvisionedSubscriberId");
4606         provisionedSubscriberIdField.setAccessible(true);
4607         provisionedSubscriberIdField.set(mSatelliteControllerUT, new HashMap<>());
4608         Field subscriberIdPerSubField = SatelliteController.class.getDeclaredField(
4609                 "mSubscriberIdPerSub");
4610         subscriberIdPerSubField.setAccessible(true);
4611         subscriberIdPerSubField.set(mSatelliteControllerUT, new HashMap<>());
4612         Field lastConfiguredIccIdField = SatelliteController.class.getDeclaredField(
4613                 "mLastConfiguredIccId");
4614         lastConfiguredIccIdField.setAccessible(true);
4615         lastConfiguredIccIdField.set(mSatelliteControllerUT, null);
4616         doReturn(subInfoInternal).when(mMockSubscriptionManagerService).getSubscriptionInfoInternal(
4617                 eq(SUB_ID));
4618         doReturn(subInfoInternal2).when(
4619                 mMockSubscriptionManagerService).getSubscriptionInfoInternal(eq(SUB_ID1));
4620         doReturn(mResources).when(mContext).getResources();
4621         doReturn("package").when(mResources).getString(
4622                 eq(R.string.config_satellite_gateway_service_package));
4623         doReturn("className").when(mResources).getString(
4624                 eq(R.string.config_satellite_carrier_roaming_esos_provisioned_class));
4625         doReturn(true).when(mResources).getBoolean(
4626                 eq(R.bool.config_support_disable_satellite_while_enable_in_progress));
4627     }
4628 
getExpectedSatelliteSubscriberInfoList()4629     private List<SatelliteSubscriberInfo> getExpectedSatelliteSubscriberInfoList() {
4630         List<SatelliteSubscriberInfo> list = new ArrayList<>();
4631         list.add(new SatelliteSubscriberInfo.Builder().setSubscriberId(mSubscriberId).setCarrierId(
4632                 mCarrierId).setNiddApn(mNiddApn).setSubscriptionId(SUB_ID).setSubscriberIdType(
4633                 SatelliteSubscriberInfo.SUBSCRIBER_ID_TYPE_IMSI_MSISDN).build());
4634         list.add(new SatelliteSubscriberInfo.Builder().setSubscriberId(mSubscriberId2).setCarrierId(
4635                 mCarrierId).setNiddApn(mNiddApn).setSubscriptionId(SUB_ID1).setSubscriberIdType(
4636                 SatelliteSubscriberInfo.SUBSCRIBER_ID_TYPE_ICCID).build());
4637         return list;
4638     }
4639 
4640     @Test
testCheckForSubscriberIdChange_noChanged()4641     public void testCheckForSubscriberIdChange_noChanged() {
4642         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4643 
4644         String imsi = "012345";
4645         String oldMsisdn = "1234567890";
4646         String newMsisdn = "1234567890";
4647         List<SubscriptionInfo> allSubInfos = new ArrayList<>();
4648         Optional<String> getSubscriberId;
4649         SubscriptionInfoInternal subInfoInternal =
4650                 new SubscriptionInfoInternal.Builder().setCarrierId(0)
4651                         .setImsi(imsi).build();
4652 
4653         when(mSubscriptionInfo.getSubscriptionId()).thenReturn(SUB_ID);
4654         allSubInfos.add(mSubscriptionInfo);
4655         doReturn(" ").when(mContext).getOpPackageName();
4656         doReturn(" ").when(mContext).getAttributionTag();
4657         when(mMockSubscriptionManagerService.getAllSubInfoList(anyString(), anyString()))
4658                 .thenReturn(allSubInfos);
4659         when(mSubscriptionInfo.isSatelliteESOSSupported()).thenReturn(true);
4660         when(mMockSubscriptionManagerService.getSubscriptionInfoInternal(SUB_ID))
4661                 .thenReturn(subInfoInternal);
4662 
4663         try {
4664             Field field = SatelliteController.class.getDeclaredField("mInjectSubscriptionManager");
4665             field.setAccessible(true);
4666             field.set(mSatelliteControllerUT, mSubscriptionManager);
4667         } catch (Exception e) {
4668             loge("Exception InjectSubscriptionManager e: " + e);
4669         }
4670         when(mSubscriptionManager.getPhoneNumber(SUB_ID)).thenReturn(newMsisdn);
4671         when(mSubscriptionInfo.isOnlyNonTerrestrialNetwork()).thenReturn(false);
4672         mSatelliteControllerUT.subscriberIdPerSub().put(imsi + oldMsisdn, SUB_ID);
4673 
4674         getSubscriberId = mSatelliteControllerUT.subscriberIdPerSub().entrySet().stream()
4675                 .filter(entry -> entry.getValue().equals(SUB_ID))
4676                 .map(Map.Entry::getKey).findFirst();
4677         assertEquals(imsi + newMsisdn, getSubscriberId.get());
4678 
4679         setComponentName();
4680         mSatelliteControllerUT.subsInfoListPerPriority().computeIfAbsent(
4681                         getKeyPriority(mSubscriptionInfo), k -> new ArrayList<>())
4682                 .add(mSubscriptionInfo);
4683         mSatelliteControllerUT.evaluateESOSProfilesPrioritizationTest();
4684         // Verify that broadcast has not been sent.
4685         verify(mContext, times(0)).sendBroadcast(any(Intent.class));
4686     }
4687 
4688     @Test
testCheckForSubscriberIdChange_changed()4689     public void testCheckForSubscriberIdChange_changed() {
4690         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4691         mCarrierConfigBundle.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
4692         List<SubscriptionInfo> allSubInfos = new ArrayList<>();
4693 
4694         String imsi = "012345";
4695         String oldMsisdn = "1234567890";
4696         String newMsisdn = "4567891234";
4697 
4698         Optional<String> getSubscriberId;
4699         SubscriptionInfoInternal subInfoInternal =
4700                 new SubscriptionInfoInternal.Builder().setCarrierId(0).setImsi(imsi).build();
4701 
4702         when(mSubscriptionInfo.getSubscriptionId()).thenReturn(SUB_ID);
4703         allSubInfos.add(mSubscriptionInfo);
4704         doReturn(" ").when(mContext).getOpPackageName();
4705         doReturn(" ").when(mContext).getAttributionTag();
4706         when(mMockSubscriptionManagerService.getAllSubInfoList(anyString(), anyString()))
4707                 .thenReturn(allSubInfos);
4708 
4709         when(mSubscriptionInfo.isSatelliteESOSSupported()).thenReturn(true);
4710         when(mSubscriptionInfo.isActive()).thenReturn(true);
4711         when(mMockSubscriptionManagerService.getSubscriptionInfoInternal(SUB_ID))
4712                 .thenReturn(subInfoInternal);
4713 
4714         try {
4715             Field field = SatelliteController.class.getDeclaredField("mInjectSubscriptionManager");
4716             field.setAccessible(true);
4717             field.set(mSatelliteControllerUT, mSubscriptionManager);
4718         } catch (Exception e) {
4719             loge("Exception InjectSubscriptionManager e: " + e);
4720         }
4721         when(mSubscriptionManager.getPhoneNumber(SUB_ID)).thenReturn(newMsisdn);
4722         when(mSubscriptionInfo.isOnlyNonTerrestrialNetwork()).thenReturn(false);
4723         mSatelliteControllerUT.subscriberIdPerSub().put(imsi + oldMsisdn, SUB_ID);
4724 
4725         getSubscriberId = mSatelliteControllerUT.subscriberIdPerSub().entrySet().stream()
4726                 .filter(entry -> entry.getValue().equals(SUB_ID))
4727                 .map(Map.Entry::getKey).findFirst();
4728         assertNotEquals(imsi + newMsisdn, getSubscriberId.get());
4729 
4730         setComponentName();
4731         mSatelliteControllerUT.subsInfoListPerPriority().computeIfAbsent(
4732                         getKeyPriority(mSubscriptionInfo), k -> new ArrayList<>())
4733                 .add(mSubscriptionInfo);
4734         mSatelliteControllerUT.evaluateESOSProfilesPrioritizationTest();
4735         // Verify that broadcast has been sent.
4736         verify(mContext, times(1)).sendBroadcast(any(Intent.class));
4737     }
4738 
4739     @Test
testRegisterForSatelliteCommunicationAccessStateChanged()4740     public void testRegisterForSatelliteCommunicationAccessStateChanged() throws Exception {
4741         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4742         mContextFixture.putIntArrayResource(
4743                 R.array.config_verizon_satellite_enabled_tagids,
4744                 new int[]{1001});
4745         when(mContext.getResources()).thenReturn(mResources);
4746         when(mResources.getIntArray(
4747                 R.array.config_verizon_satellite_enabled_tagids)).thenReturn(new int[]{1001});
4748         // carrierID is same as SUBID for this test
4749         final int carrierSubId = SUB_ID;
4750         final int oemSubId = SUB_ID1;
4751         final String carrierSubscriberId = mSubscriberId;
4752         final String oemSubscriberId = mSubscriberId2;
4753         mCarrierConfigBundle.putBoolean(KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
4754         setSatelliteSubscriberTesting(false);
4755         invokeCarrierConfigChanged();
4756 
4757         Field provisionedSubscriberIdField = SatelliteController.class.getDeclaredField(
4758                 "mProvisionedSubscriberId");
4759         provisionedSubscriberIdField.setAccessible(true);
4760         Map<String, Boolean> testProvisionedSubscriberId = new HashMap<>();;
4761         testProvisionedSubscriberId.put(carrierSubscriberId, true);
4762         testProvisionedSubscriberId.put(oemSubscriberId, true);
4763         provisionedSubscriberIdField.set(mSatelliteControllerUT, testProvisionedSubscriberId);
4764 
4765         Field currentLocationTagIdsField = SatelliteController.class.getDeclaredField(
4766                 "mCurrentLocationTagIds");
4767         currentLocationTagIdsField.setAccessible(true);
4768 
4769         setComponentName();
4770         mSatelliteControllerUT.setIsSatelliteAllowedState(true);
4771 
4772         mSatelliteControllerUT.registerForSatelliteCommunicationAccessStateChanged();
4773 
4774         // Test satelliteAccessConfigCallback.onSuccess
4775         // with current location NOT supporting carrier satellite
4776         // OEM satellite subscription should be selected
4777         currentLocationTagIdsField.set(mSatelliteControllerUT, Arrays.asList(100));
4778 
4779         mSatelliteControllerUT.subsInfoListPerPriority().computeIfAbsent(
4780                         getKeyPriority(testSubscriptionInfo), k -> new ArrayList<>())
4781                 .add(testSubscriptionInfo);
4782         mSatelliteControllerUT.subsInfoListPerPriority().computeIfAbsent(
4783                         getKeyPriority(testSubscriptionInfo2), k -> new ArrayList<>())
4784                 .add(testSubscriptionInfo2);
4785 
4786         mSatelliteControllerUT.selectedSatelliteSubId = SUB_ID1;
4787         mSatelliteControllerUT.evaluateESOSProfilesPrioritizationTest();
4788         processAllMessages();
4789         assertEquals(oemSubId, mSatelliteControllerUT.getSelectedSatelliteSubId());
4790 
4791         // Test satelliteAccessConfigCallback.onSuccess
4792         // with current location supporting carrier satellite
4793         // Carrier satellite subscription should be selected
4794         currentLocationTagIdsField.set(mSatelliteControllerUT, Arrays.asList(1001, 100));
4795 
4796         mSatelliteControllerUT.subsInfoListPerPriority().computeIfAbsent(
4797                         getKeyPriority(testSubscriptionInfo), k -> new ArrayList<>())
4798                 .add(testSubscriptionInfo);
4799         mSatelliteControllerUT.subsInfoListPerPriority().computeIfAbsent(
4800                         getKeyPriority(testSubscriptionInfo2), k -> new ArrayList<>())
4801                 .add(testSubscriptionInfo2);
4802 
4803         mSatelliteControllerUT.selectedSatelliteSubId = SUB_ID;
4804         mSatelliteControllerUT.evaluateESOSProfilesPrioritizationTest();
4805         processAllMessages();
4806         assertEquals(carrierSubId, mSatelliteControllerUT.getSelectedSatelliteSubId());
4807     }
4808 
4809 
4810     @Test
testProvisionStatusPerSubscriberIdGetFromDb()4811     public void testProvisionStatusPerSubscriberIdGetFromDb() throws Exception {
4812         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4813 
4814         setSatelliteSubscriberTesting(true);
4815         // Check if the cache is not updated when the value read from the database is false.
4816         verifyProvisionStatusPerSubscriberIdGetFromDb(false);
4817 
4818         // Check if the cache is updated when the value read from the database is true.
4819         verifyProvisionStatusPerSubscriberIdGetFromDb(true);
4820     }
4821 
4822     @Test
testProvisionStatusPerSubscriberIdStoreToDb()4823     public void testProvisionStatusPerSubscriberIdStoreToDb() throws Exception {
4824         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4825 
4826         setSatelliteSubscriberTesting(true);
4827         // Check if the cache is not updated when the value read from the database is false.
4828         verifyProvisionStatusPerSubscriberIdGetFromDb(false);
4829 
4830         List<SatelliteSubscriberInfo> inputList = getExpectedSatelliteSubscriberInfoList();
4831         verifyProvisionSatellite(inputList);
4832         verify(mMockSubscriptionManagerService).setIsSatelliteProvisionedForNonIpDatagram(
4833                 eq(SUB_ID), eq(true));
4834     }
4835 
4836     @Test
testIsCarrierRoamingNtnAvailableServicesForManualConnect()4837     public void testIsCarrierRoamingNtnAvailableServicesForManualConnect() {
4838         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4839         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
4840         // CARRIER_ROAMING_NTN_CONNECT_MANUAL: 1
4841         mCarrierConfigBundle.putInt(KEY_CARRIER_ROAMING_NTN_CONNECT_TYPE_INT, 1);
4842 
4843         mSatelliteControllerUT.setSatellitePhone(1);
4844         processAllMessages();
4845         when(mContext.getPackageManager()).thenReturn(mMockPManager);
4846         try {
4847             when(mMockPManager.getApplicationInfo(anyString(),
4848                     anyInt())).thenReturn(getApplicationInfo());
4849         } catch (PackageManager.NameNotFoundException e) {
4850             logd("NameNotFoundException");
4851         }
4852         assertTrue(mSatelliteControllerUT
4853                 .isP2PSmsDisallowedOnCarrierRoamingNtn(/*subId*/ SUB_ID));
4854     }
4855 
4856     @Test
testIsCarrierRoamingNtnAvailableServicesForAutomaticConnect()4857     public void testIsCarrierRoamingNtnAvailableServicesForAutomaticConnect() {
4858         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4859         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
4860         // CARRIER_ROAMING_NTN_CONNECT_AUTOMATIC: 0
4861         mCarrierConfigBundle.putInt(KEY_CARRIER_ROAMING_NTN_CONNECT_TYPE_INT, 0);
4862 
4863         mSatelliteControllerUT.setSatellitePhone(1);
4864         processAllMessages();
4865         when(mContext.getPackageManager()).thenReturn(mMockPManager);
4866         try {
4867             when(mMockPManager.getApplicationInfo(anyString(),
4868                     anyInt())).thenReturn(getApplicationInfo());
4869         } catch (PackageManager.NameNotFoundException e) {
4870             logd("NameNotFoundException");
4871         }
4872         // If it is automatic connection case, it is not support the callback.
4873         assertFalse(mSatelliteControllerUT
4874                 .isP2PSmsDisallowedOnCarrierRoamingNtn(/*subId*/ SUB_ID));
4875     }
4876 
getApplicationInfo()4877     ApplicationInfo getApplicationInfo() {
4878         ApplicationInfo applicationInfo = new ApplicationInfo();
4879         applicationInfo.metaData = new Bundle();
4880         applicationInfo.metaData.putBoolean(
4881                 METADATA_SATELLITE_MANUAL_CONNECT_P2P_SUPPORT, true);
4882         return applicationInfo;
4883     }
4884 
4885     @Test
testRegisterApplicationStateChanged()4886     public void testRegisterApplicationStateChanged() {
4887         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4888         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, false);
4889         when(mMockSubscriptionManagerService.getActiveSubIdList(true))
4890                 .thenReturn(new int[]{SUB_ID1});
4891 
4892         ArgumentCaptor<IntentFilter> intentFilterCaptor =
4893                 ArgumentCaptor.forClass(IntentFilter.class);
4894         ArgumentCaptor<BroadcastReceiver> receiverCaptor =
4895                 ArgumentCaptor.forClass(BroadcastReceiver.class);
4896         verify(mContext).registerReceiver(receiverCaptor.capture(), intentFilterCaptor.capture(),
4897                 anyInt());
4898 
4899         BroadcastReceiver receiver = receiverCaptor.getValue();
4900         mSatelliteControllerUT =
4901                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
4902         assertFalse(mSatelliteControllerUT.isApplicationUpdated);
4903         Intent intent = new Intent(Intent.ACTION_PACKAGE_ADDED);
4904         intent.setData(Uri.parse("com.example.app"));
4905         receiver.onReceive(mContext, intent);
4906         CountDownLatch latch1 = new CountDownLatch(1);
4907         new Handler(Looper.getMainLooper()).postDelayed(() -> {
4908             latch1.countDown();
4909         }, 100);
4910         try {
4911             latch1.await();
4912         } catch (InterruptedException e) {
4913         }
4914         assertTrue(mSatelliteControllerUT.isApplicationUpdated);
4915         mSatelliteControllerUT =
4916                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
4917         assertFalse(mSatelliteControllerUT.isApplicationUpdated);
4918         intent = new Intent(Intent.ACTION_PACKAGE_REPLACED);
4919         intent.setData(Uri.parse("com.example.app"));
4920         receiver.onReceive(mContext, intent);
4921         CountDownLatch latch2 = new CountDownLatch(1);
4922         new Handler(Looper.getMainLooper()).postDelayed(() -> {
4923             latch2.countDown();
4924         }, 100);
4925         try {
4926             latch2.await();
4927         } catch (InterruptedException e) {
4928         }
4929         assertTrue(mSatelliteControllerUT.isApplicationUpdated);
4930         mSatelliteControllerUT =
4931                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
4932         assertFalse(mSatelliteControllerUT.isApplicationUpdated);
4933         intent = new Intent(Intent.ACTION_PACKAGE_REMOVED);
4934         intent.setData(Uri.parse("com.example.app"));
4935         receiver.onReceive(mContext, intent);
4936         CountDownLatch latch3 = new CountDownLatch(1);
4937         new Handler(Looper.getMainLooper()).postDelayed(() -> {
4938             latch3.countDown();
4939         }, 100);
4940         try {
4941             latch3.await();
4942         } catch (InterruptedException e) {
4943         }
4944         assertTrue(mSatelliteControllerUT.isApplicationUpdated);
4945         mSatelliteControllerUT =
4946                 new TestSatelliteController(mContext, Looper.myLooper(), mFeatureFlags);
4947         assertFalse(mSatelliteControllerUT.isApplicationUpdated);
4948         intent = new Intent(Intent.ACTION_PACKAGE_ADDED);
4949         intent.setData(Uri.parse("com.example.different"));
4950         receiver.onReceive(mContext, intent);
4951         CountDownLatch latch4 = new CountDownLatch(1);
4952         new Handler(Looper.getMainLooper()).postDelayed(() -> {
4953             latch4.countDown();
4954         }, 100);
4955         try {
4956             latch4.await();
4957         } catch (InterruptedException e) {
4958         }
4959         assertFalse(mSatelliteControllerUT.isApplicationUpdated);
4960     }
4961 
4962     @Test
testUpdateSystemSelectionChannels()4963     public void testUpdateSystemSelectionChannels() {
4964         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
4965 
4966         String mccmnc = "123455";
4967         int[] bands1 = {200, 201, 202};
4968         IntArray intArraybands1 = new IntArray(3);
4969         intArraybands1.addAll(bands1);
4970         int[] earfcns1 = {300, 301, 310, 311};
4971         IntArray intArrayEarfcns1 = new IntArray(4);
4972         intArrayEarfcns1.addAll(earfcns1);
4973         String seed1 = "test-seed-satellite1";
4974         UUID uuid1 = UUID.nameUUIDFromBytes(seed1.getBytes());
4975         SatellitePosition satellitePosition1 = new SatellitePosition(0, 35876);
4976         EarfcnRange earfcnRange1 = new EarfcnRange(301, 300);
4977         EarfcnRange earfcnRange2 = new EarfcnRange(311, 310);
4978         List<EarfcnRange> earfcnRangeList1 = new ArrayList<>(
4979                 Arrays.asList(earfcnRange1, earfcnRange2));
4980         SatelliteInfo satelliteInfo1 = new SatelliteInfo(uuid1, satellitePosition1, Arrays.stream(
4981                 bands1).boxed().collect(Collectors.toList()), earfcnRangeList1);
4982         int[] tagIds = {1, 2, 3};
4983         IntArray intArrayTagIds = new IntArray(3);
4984         intArrayTagIds.addAll(tagIds);
4985         SystemSelectionSpecifier systemSelectionSpecifier1 = new SystemSelectionSpecifier(mccmnc,
4986                 intArraybands1, intArrayEarfcns1, new SatelliteInfo[]{satelliteInfo1},
4987                 intArrayTagIds);
4988 
4989         setUpResponseForUpdateSystemSelectionChannels(SATELLITE_RESULT_ERROR);
4990         mSatelliteControllerUT.updateSystemSelectionChannels(
4991                 new ArrayList<>(List.of(systemSelectionSpecifier1)),
4992                 mSystemSelectionChannelUpdatedReceiver);
4993         processAllMessages();
4994         assertTrue(waitForRequestUpdateSystemSelectionChannelResult(1));
4995         assertEquals(SATELLITE_RESULT_ERROR, mQueriedSystemSelectionChannelUpdatedResultCode);
4996 
4997         // Verify whether callback receives expected result
4998         setUpResponseForUpdateSystemSelectionChannels(SATELLITE_RESULT_SUCCESS);
4999         mSatelliteControllerUT.updateSystemSelectionChannels(
5000                 new ArrayList<>(List.of(systemSelectionSpecifier1)),
5001                 mSystemSelectionChannelUpdatedReceiver);
5002         processAllMessages();
5003         assertTrue(waitForRequestUpdateSystemSelectionChannelResult(1));
5004         assertEquals(SATELLITE_RESULT_SUCCESS, mQueriedSystemSelectionChannelUpdatedResultCode);
5005 
5006         // Verify whether SatelliteModemInterface API was invoked and data is valid, when single
5007         // data was provided.
5008         ArgumentCaptor<List<SystemSelectionSpecifier>> systemSelectionSpecifierListCaptor =
5009                 ArgumentCaptor.forClass(List.class);
5010         verify(mMockSatelliteModemInterface, times(2)).updateSystemSelectionChannels(
5011                 systemSelectionSpecifierListCaptor.capture(), any(Message.class));
5012         List<SystemSelectionSpecifier> capturedList = systemSelectionSpecifierListCaptor.getValue();
5013         SystemSelectionSpecifier systemSelectionSpecifier = capturedList.getFirst();
5014 
5015         assertEquals(mccmnc, systemSelectionSpecifier.getMccMnc());
5016         int[] actualBandsArray = systemSelectionSpecifier.getBands();
5017         assertArrayEquals(bands1, actualBandsArray);
5018         int[] actualEarfcnsArray = systemSelectionSpecifier.getEarfcns();
5019         assertArrayEquals(earfcns1, actualEarfcnsArray);
5020         assertArrayEquals(new SatelliteInfo[]{satelliteInfo1},
5021                 systemSelectionSpecifier.getSatelliteInfos().toArray(new SatelliteInfo[0]));
5022         int[] actualTagIdArray = systemSelectionSpecifier.getTagIds();
5023         assertArrayEquals(tagIds, actualTagIdArray);
5024 
5025         // Verify whether SatelliteModemInterface API was invoked and data is valid, when list
5026         // of data was provided.
5027         int[] bands2 = {210, 211, 212};
5028         IntArray intArraybands2 = new IntArray(3);
5029         intArraybands2.addAll(bands2);
5030         int[] earfcns2 = {320, 321, 330, 331};
5031         IntArray intArrayEarfcns2 = new IntArray(4);
5032         intArrayEarfcns2.addAll(earfcns2);
5033         String seed2 = "test-seed-satellite2";
5034         UUID uuid2 = UUID.nameUUIDFromBytes(seed2.getBytes());
5035         SatellitePosition satellitePosition2 = new SatellitePosition(120, 35876);
5036         EarfcnRange earfcnRange3 = new EarfcnRange(321, 320);
5037         EarfcnRange earfcnRange4 = new EarfcnRange(331, 330);
5038         List<EarfcnRange> earfcnRangeList2 = new ArrayList<>(
5039                 Arrays.asList(earfcnRange3, earfcnRange4));
5040         SatelliteInfo satelliteInfo2 = new SatelliteInfo(uuid2, satellitePosition2, Arrays.stream(
5041                 bands1).boxed().collect(Collectors.toList()), earfcnRangeList2);
5042         SystemSelectionSpecifier systemSelectionSpecifier2 = new SystemSelectionSpecifier(mccmnc,
5043                 intArraybands2, intArrayEarfcns2, new SatelliteInfo[]{satelliteInfo2},
5044                 intArrayTagIds);
5045 
5046         // Verify whether callback receives expected result
5047         setUpResponseForUpdateSystemSelectionChannels(SATELLITE_RESULT_SUCCESS);
5048         mSatelliteControllerUT.updateSystemSelectionChannels(
5049                 new ArrayList<>(List.of(systemSelectionSpecifier1, systemSelectionSpecifier2)),
5050                 mSystemSelectionChannelUpdatedReceiver);
5051         processAllMessages();
5052         assertTrue(waitForRequestUpdateSystemSelectionChannelResult(1));
5053         assertEquals(SATELLITE_RESULT_SUCCESS, mQueriedSystemSelectionChannelUpdatedResultCode);
5054 
5055         // Verify whether SatelliteModemInterface API was invoked and data is valid,
5056         verify(mMockSatelliteModemInterface, times(3)).updateSystemSelectionChannels(
5057                 systemSelectionSpecifierListCaptor.capture(), any(Message.class));
5058         capturedList = systemSelectionSpecifierListCaptor.getValue();
5059         SystemSelectionSpecifier capturedSystemSelectionSpecifier1 = capturedList.getFirst();
5060         SystemSelectionSpecifier capturedSystemSelectionSpecifier2 = capturedList.get(1);
5061 
5062         // Verify first SystemSelectionSpecifier
5063         assertEquals(mccmnc, systemSelectionSpecifier.getMccMnc());
5064         actualBandsArray = capturedSystemSelectionSpecifier1.getBands();
5065         assertArrayEquals(bands1, actualBandsArray);
5066         actualEarfcnsArray = capturedSystemSelectionSpecifier1.getEarfcns();
5067         assertArrayEquals(earfcns1, actualEarfcnsArray);
5068         assertArrayEquals(new SatelliteInfo[]{satelliteInfo1},
5069                 capturedSystemSelectionSpecifier1.getSatelliteInfos().toArray(
5070                         new SatelliteInfo[0]));
5071         actualTagIdArray = capturedSystemSelectionSpecifier1.getTagIds();
5072         assertArrayEquals(tagIds, actualTagIdArray);
5073 
5074         // Verify second SystemSelectionSpecifier
5075         assertEquals(mccmnc, systemSelectionSpecifier.getMccMnc());
5076         actualBandsArray = capturedSystemSelectionSpecifier2.getBands();
5077         assertArrayEquals(bands2, actualBandsArray);
5078         actualEarfcnsArray = capturedSystemSelectionSpecifier2.getEarfcns();
5079         assertArrayEquals(earfcns2, actualEarfcnsArray);
5080         assertArrayEquals(new SatelliteInfo[]{satelliteInfo2},
5081                 capturedSystemSelectionSpecifier2.getSatelliteInfos().toArray(
5082                         new SatelliteInfo[0]));
5083         actualTagIdArray = capturedSystemSelectionSpecifier2.getTagIds();
5084         assertArrayEquals(tagIds, actualTagIdArray);
5085     }
5086 
verifyProvisionStatusPerSubscriberIdGetFromDb(boolean provision)5087     private void verifyProvisionStatusPerSubscriberIdGetFromDb(boolean provision) {
5088         doReturn(provision).when(
5089                 mMockSubscriptionManagerService).isSatelliteProvisionedForNonIpDatagram(anyInt());
5090         mCarrierConfigBundle.putString(KEY_SATELLITE_NIDD_APN_NAME_STRING, mNiddApn);
5091         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ESOS_SUPPORTED_BOOL, true);
5092         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
5093                 : mCarrierConfigChangedListenerList) {
5094             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
5095                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
5096             );
5097         }
5098         moveTimeForward(TimeUnit.MINUTES.toMillis(1));
5099         processAllMessages();
5100         mSatelliteControllerUT.requestSatelliteSubscriberProvisionStatus(
5101                 mRequestSatelliteSubscriberProvisionStatusReceiver);
5102         moveTimeForward(TimeUnit.MINUTES.toMillis(1));
5103         processAllMessages();
5104         assertEquals(SATELLITE_RESULT_SUCCESS,
5105                 mRequestSatelliteSubscriberProvisionStatusResultCode);
5106         assertEquals(provision,
5107                 mRequestSatelliteSubscriberProvisionStatusResultList.get(0).isProvisioned());
5108     }
5109 
setComponentName()5110     private void setComponentName() {
5111         when(mSatelliteControllerUT.getStringFromOverlayConfigTest(
5112                 R.string.config_satellite_gateway_service_package))
5113                 .thenReturn("com.example.package");
5114         when(mSatelliteControllerUT.getStringFromOverlayConfigTest(
5115                 R.string.config_satellite_carrier_roaming_esos_provisioned_class))
5116                 .thenReturn("com.example.class");
5117     }
5118 
getKeyPriority(SubscriptionInfo subscriptionInfo)5119     private int getKeyPriority(SubscriptionInfo subscriptionInfo) {
5120         boolean isActive = subscriptionInfo.isActive();
5121         boolean isNtnOnly = subscriptionInfo.isOnlyNonTerrestrialNetwork();
5122         boolean isESOSSupported = subscriptionInfo.isSatelliteESOSSupported();
5123         boolean isCarrierSatelliteHigherPriority =
5124                 mSatelliteControllerUT.isCarrierSatelliteHigherPriorityTest(
5125                         subscriptionInfo);
5126 
5127         int keyPriority;
5128         if (isESOSSupported && isActive && isCarrierSatelliteHigherPriority) {
5129             keyPriority = 1;
5130         } else if (isNtnOnly) {
5131             keyPriority = 2;
5132         } else if (isESOSSupported) {
5133             keyPriority = 3;
5134         } else {
5135             keyPriority = -1;
5136         }
5137         return keyPriority;
5138     }
5139 
resetSatelliteControllerUTEnabledState()5140     private void resetSatelliteControllerUTEnabledState() {
5141         logd("resetSatelliteControllerUTEnabledState");
5142         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_RADIO_NOT_AVAILABLE);
5143         doNothing().when(mMockSatelliteModemInterface)
5144                 .setSatelliteServicePackageName(anyString());
5145         mSatelliteControllerUT.setSatelliteServicePackageName("TestSatelliteService", null);
5146         processAllMessages();
5147 
5148         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
5149         setProvisionedState(false);
5150         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
5151         setProvisionedState(true);
5152         processAllMessages();
5153         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
5154     }
5155 
resetSatelliteControllerUT()5156     private void resetSatelliteControllerUT() {
5157         logd("resetSatelliteControllerUT");
5158         // Trigger cleanUpResources
5159         sendSatelliteModemStateChangedEvent(SATELLITE_MODEM_STATE_UNAVAILABLE, null);
5160         processAllMessages();
5161 
5162         // Reset all cached states
5163         setUpResponseForRequestIsSatelliteSupported(false, SATELLITE_RESULT_RADIO_NOT_AVAILABLE);
5164         doNothing().when(mMockSatelliteModemInterface)
5165                 .setSatelliteServicePackageName(anyString());
5166         mSatelliteControllerUT.setSatelliteServicePackageName("TestSatelliteService", null);
5167         processAllMessages();
5168     }
5169 
resetSatelliteControllerUTToSupportedAndProvisionedState()5170     private void resetSatelliteControllerUTToSupportedAndProvisionedState() {
5171         resetSatelliteControllerUT();
5172         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
5173         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
5174         setProvisionedState(true);
5175         processAllMessages();
5176         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
5177     }
5178 
resetSatelliteControllerUTToOffAndProvisionedState()5179     private void resetSatelliteControllerUTToOffAndProvisionedState() {
5180         resetSatelliteControllerUTToSupportedAndProvisionedState();
5181         // Clean up pending resources and move satellite controller to OFF state.
5182         sendSatelliteModemStateChangedEvent(SATELLITE_MODEM_STATE_UNAVAILABLE, null);
5183         mSatelliteControllerUT.moveSatelliteToOffStateAndCleanUpResources(
5184                 SATELLITE_RESULT_REQUEST_ABORTED);
5185         processAllMessages();
5186         verifySatelliteEnabled(false, SATELLITE_RESULT_SUCCESS);
5187     }
5188 
resetSatelliteControllerUTToOnAndProvisionedState()5189     private void resetSatelliteControllerUTToOnAndProvisionedState() {
5190         resetSatelliteControllerUTToOffAndProvisionedState();
5191         setRadioPower(true);
5192         processAllMessages();
5193 
5194         mIIntegerConsumerResults.clear();
5195         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
5196         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
5197         processAllMessages();
5198         assertTrue(waitForIIntegerConsumerResult(1));
5199         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
5200         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
5201     }
5202 
setUpResponseForRequestIsSatelliteEnabled(boolean isSatelliteEnabled, @SatelliteManager.SatelliteResult int error)5203     private void setUpResponseForRequestIsSatelliteEnabled(boolean isSatelliteEnabled,
5204             @SatelliteManager.SatelliteResult int error) {
5205         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5206                 ? null : new SatelliteException(error);
5207         doAnswer(invocation -> {
5208             Message message = (Message) invocation.getArguments()[0];
5209             int[] enabled = new int[] {isSatelliteEnabled ? 1 : 0};
5210             AsyncResult.forMessage(message, enabled, exception);
5211             message.sendToTarget();
5212             return null;
5213         }).when(mMockSatelliteModemInterface).requestIsSatelliteEnabled(any(Message.class));
5214         mSatelliteControllerUT.isSatelliteEnabledOrBeingEnabled = isSatelliteEnabled;
5215     }
5216 
setUpResponseForRequestIsSatelliteSupported( boolean isSatelliteSupported, @SatelliteManager.SatelliteResult int error)5217     private void setUpResponseForRequestIsSatelliteSupported(
5218             boolean isSatelliteSupported, @SatelliteManager.SatelliteResult int error) {
5219         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5220                 ? null : new SatelliteException(error);
5221         doAnswer(invocation -> {
5222             Message message = (Message) invocation.getArguments()[0];
5223             AsyncResult.forMessage(message, isSatelliteSupported, exception);
5224             message.sendToTarget();
5225             return null;
5226         }).when(mMockSatelliteModemInterface).requestIsSatelliteSupported(any(Message.class));
5227     }
5228 
setUpResponseForRequestTimeForNextSatelliteVisibility( int satelliteVisibilityTime, @SatelliteManager.SatelliteResult int error)5229     private void setUpResponseForRequestTimeForNextSatelliteVisibility(
5230             int satelliteVisibilityTime, @SatelliteManager.SatelliteResult int error) {
5231         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5232                 ? null : new SatelliteException(error);
5233         int[] visibilityTime = new int[]{satelliteVisibilityTime};
5234         doAnswer(invocation -> {
5235             Message message = (Message) invocation.getArguments()[0];
5236             AsyncResult.forMessage(message, visibilityTime, exception);
5237             message.sendToTarget();
5238             return null;
5239         }).when(mMockSatelliteModemInterface)
5240                 .requestTimeForNextSatelliteVisibility(any(Message.class));
5241     }
5242 
setUpNullResponseForRequestTimeForNextSatelliteVisibility( @atelliteManager.SatelliteResult int error)5243     private void setUpNullResponseForRequestTimeForNextSatelliteVisibility(
5244             @SatelliteManager.SatelliteResult int error) {
5245         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5246                 ? null : new SatelliteException(error);
5247         doAnswer(invocation -> {
5248             Message message = (Message) invocation.getArguments()[0];
5249             AsyncResult.forMessage(message, null, exception);
5250             message.sendToTarget();
5251             return null;
5252         }).when(mMockSatelliteModemInterface)
5253                 .requestTimeForNextSatelliteVisibility(any(Message.class));
5254     }
5255 
setUpResponseForRequestIsSatelliteProvisioned( boolean isSatelliteProvisioned, @SatelliteManager.SatelliteResult int error)5256     private void setUpResponseForRequestIsSatelliteProvisioned(
5257             boolean isSatelliteProvisioned, @SatelliteManager.SatelliteResult int error) {
5258         mSatelliteControllerUT.setSatelliteProvisioned(isSatelliteProvisioned);
5259     }
5260 
setUpResponseForRequestSatelliteEnabled( boolean enabled, boolean demoMode, boolean emergency, @SatelliteManager.SatelliteResult int error)5261     private void setUpResponseForRequestSatelliteEnabled(
5262             boolean enabled, boolean demoMode, boolean emergency,
5263             @SatelliteManager.SatelliteResult int error) {
5264         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5265                 ? null : new SatelliteException(error);
5266         doAnswer(invocation -> {
5267             if (exception == null && !enabled) {
5268                 sendSatelliteModemStateChangedEvent(SATELLITE_MODEM_STATE_OFF, null);
5269             }
5270             Message message = (Message) invocation.getArguments()[1];
5271             AsyncResult.forMessage(message, null, exception);
5272             message.sendToTarget();
5273             return null;
5274         }).when(mMockSatelliteModemInterface)
5275                 .requestSatelliteEnabled(any(SatelliteModemEnableRequestAttributes.class),
5276                         any(Message.class));
5277     }
5278 
setUpResponseForRequestSetSatelliteEnabledForCarrier( boolean enabled, @SatelliteManager.SatelliteResult int error)5279     private void setUpResponseForRequestSetSatelliteEnabledForCarrier(
5280             boolean enabled, @SatelliteManager.SatelliteResult int error) {
5281         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5282                 ? null : new SatelliteException(error);
5283         doAnswer(invocation -> {
5284             Message message = (Message) invocation.getArguments()[2];
5285             AsyncResult.forMessage(message, null, exception);
5286             message.sendToTarget();
5287             return null;
5288         }).when(mPhone)
5289                 .setSatelliteEnabledForCarrier(anyInt(), eq(enabled), any(Message.class));
5290     }
5291 
setUpNoResponseForRequestSatelliteEnabled(boolean enabled, boolean demoMode, boolean emergency)5292     private void setUpNoResponseForRequestSatelliteEnabled(boolean enabled, boolean demoMode,
5293             boolean emergency) {
5294         doNothing().when(mMockSatelliteModemInterface)
5295                 .requestSatelliteEnabled(eq(new SatelliteModemEnableRequestAttributes(
5296                                 enabled, demoMode, emergency,
5297                                 new SatelliteSubscriptionInfo("", "")
5298                         )),
5299                         any(Message.class));
5300     }
5301 
setUpResponseForRequestSatelliteCapabilities( SatelliteCapabilities satelliteCapabilities, @SatelliteManager.SatelliteResult int error)5302     private void setUpResponseForRequestSatelliteCapabilities(
5303             SatelliteCapabilities satelliteCapabilities,
5304             @SatelliteManager.SatelliteResult int error) {
5305         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5306                 ? null : new SatelliteException(error);
5307         doAnswer(invocation -> {
5308             Message message = (Message) invocation.getArguments()[0];
5309             AsyncResult.forMessage(message, satelliteCapabilities, exception);
5310             message.sendToTarget();
5311             return null;
5312         }).when(mMockSatelliteModemInterface).requestSatelliteCapabilities(any(Message.class));
5313     }
5314 
setUpResponseForRequestNtnSignalStrength( @tnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel, @SatelliteManager.SatelliteResult int error)5315     private void setUpResponseForRequestNtnSignalStrength(
5316             @NtnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel,
5317             @SatelliteManager.SatelliteResult int error) {
5318         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5319                 ? null : new SatelliteException(error);
5320         doAnswer(invocation -> {
5321             Message message = (Message) invocation.getArguments()[0];
5322             AsyncResult.forMessage(message, new NtnSignalStrength(ntnSignalStrengthLevel),
5323                     exception);
5324             message.sendToTarget();
5325             return null;
5326         }).when(mMockSatelliteModemInterface).requestNtnSignalStrength(any(Message.class));
5327     }
5328 
waitForForEvents( Semaphore semaphore, int expectedNumberOfEvents, String caller)5329     private boolean waitForForEvents(
5330             Semaphore semaphore, int expectedNumberOfEvents, String caller) {
5331         for (int i = 0; i < expectedNumberOfEvents; i++) {
5332             try {
5333                 if (!semaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)) {
5334                     loge(caller + ": Timeout to receive the expected event");
5335                     return false;
5336                 }
5337             } catch (Exception ex) {
5338                 loge(caller + ": Got exception=" + ex);
5339                 return false;
5340             }
5341         }
5342         return true;
5343     }
5344 
setUpNullResponseForRequestSatelliteCapabilities( @atelliteManager.SatelliteResult int error)5345     private void setUpNullResponseForRequestSatelliteCapabilities(
5346             @SatelliteManager.SatelliteResult int error) {
5347         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5348                 ? null : new SatelliteException(error);
5349         doAnswer(invocation -> {
5350             Message message = (Message) invocation.getArguments()[0];
5351             AsyncResult.forMessage(message, null, exception);
5352             message.sendToTarget();
5353             return null;
5354         }).when(mMockSatelliteModemInterface).requestSatelliteCapabilities(any(Message.class));
5355     }
5356 
setUpResponseForStartSatelliteTransmissionUpdates( @atelliteManager.SatelliteResult int error)5357     private void setUpResponseForStartSatelliteTransmissionUpdates(
5358             @SatelliteManager.SatelliteResult int error) {
5359         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5360                 ? null : new SatelliteException(error);
5361         doAnswer(invocation -> {
5362             Message message = (Message) invocation.getArguments()[0];
5363             AsyncResult.forMessage(message, null, exception);
5364             message.sendToTarget();
5365             return null;
5366         }).when(mMockPointingAppController).startSatelliteTransmissionUpdates(any(Message.class));
5367     }
5368 
setUpResponseForStopSatelliteTransmissionUpdates( @atelliteManager.SatelliteResult int error)5369     private void setUpResponseForStopSatelliteTransmissionUpdates(
5370             @SatelliteManager.SatelliteResult int error) {
5371         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5372                 ? null : new SatelliteException(error);
5373         doAnswer(invocation -> {
5374             Message message = (Message) invocation.getArguments()[0];
5375             AsyncResult.forMessage(message, null, exception);
5376             message.sendToTarget();
5377             return null;
5378         }).when(mMockPointingAppController).stopSatelliteTransmissionUpdates(any(Message.class));
5379     }
5380 
setUpResponseForStartSendingNtnSignalStrength( @atelliteManager.SatelliteResult int error)5381     private void setUpResponseForStartSendingNtnSignalStrength(
5382             @SatelliteManager.SatelliteResult int error) {
5383         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5384                 ? null : new SatelliteException(error);
5385         doAnswer(invocation -> {
5386             Message message = (Message) invocation.getArguments()[0];
5387             AsyncResult.forMessage(message, null, exception);
5388             message.sendToTarget();
5389             return null;
5390         }).when(mMockSatelliteModemInterface).startSendingNtnSignalStrength(any(Message.class));
5391     }
5392 
setUpResponseForStopSendingNtnSignalStrength( @atelliteManager.SatelliteResult int error)5393     private void setUpResponseForStopSendingNtnSignalStrength(
5394             @SatelliteManager.SatelliteResult int error) {
5395         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5396                 ? null : new SatelliteException(error);
5397         doAnswer(invocation -> {
5398             Message message = (Message) invocation.getArguments()[0];
5399             AsyncResult.forMessage(message, null, exception);
5400             message.sendToTarget();
5401             return null;
5402         }).when(mMockSatelliteModemInterface).stopSendingNtnSignalStrength(any(Message.class));
5403     }
5404 
setUpResponseForUpdateSystemSelectionChannels( @atelliteManager.SatelliteResult int error)5405     private void setUpResponseForUpdateSystemSelectionChannels(
5406             @SatelliteManager.SatelliteResult int error) {
5407         SatelliteException exception = (error == SATELLITE_RESULT_SUCCESS)
5408                 ? null : new SatelliteException(error);
5409         doAnswer(invocation -> {
5410             Message message = (Message) invocation.getArguments()[1];
5411             AsyncResult.forMessage(message, null, exception);
5412             message.sendToTarget();
5413             return null;
5414         }).when(mMockSatelliteModemInterface).updateSystemSelectionChannels(anyList(),
5415                 any(Message.class));
5416     }
5417 
waitForRequestIsSatelliteSupportedResult(int expectedNumberOfEvents)5418     private boolean waitForRequestIsSatelliteSupportedResult(int expectedNumberOfEvents) {
5419         for (int i = 0; i < expectedNumberOfEvents; i++) {
5420             try {
5421                 if (!mSatelliteSupportSemaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)) {
5422                     loge("Timeout to receive requestIsSatelliteSupported() callback");
5423                     return false;
5424                 }
5425             } catch (Exception ex) {
5426                 loge("waitForRequestIsSatelliteSupportedResult: Got exception=" + ex);
5427                 return false;
5428             }
5429         }
5430         return true;
5431     }
5432 
waitForRequestTimeForNextSatelliteVisibilityResult( int expectedNumberOfEvents)5433     private boolean waitForRequestTimeForNextSatelliteVisibilityResult(
5434             int expectedNumberOfEvents) {
5435         for (int i = 0; i < expectedNumberOfEvents; i++) {
5436             try {
5437                 if (!mSatelliteVisibilityTimeSemaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)) {
5438                     loge("Timeout to receive "
5439                             + "requestTimeForNextSatelliteVisibility() callback");
5440                     return false;
5441                 }
5442             } catch (Exception ex) {
5443                 loge("waitForRequestTimeForNextSatelliteVisibilityResult: Got exception=" + ex);
5444                 return false;
5445             }
5446         }
5447         return true;
5448     }
5449 
waitForRequestIsSatelliteEnabledResult(int expectedNumberOfEvents)5450     private boolean waitForRequestIsSatelliteEnabledResult(int expectedNumberOfEvents) {
5451         for (int i = 0; i < expectedNumberOfEvents; i++) {
5452             try {
5453                 if (!mIsSatelliteEnabledSemaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)) {
5454                     loge("Timeout to receive requestIsSatelliteEnabled() callback");
5455                     return false;
5456                 }
5457             } catch (Exception ex) {
5458                 loge("waitForRequestIsSatelliteEnabledResult: Got exception=" + ex);
5459                 return false;
5460             }
5461         }
5462         return true;
5463     }
5464 
waitForRequestIsSatelliteProvisionedResult(int expectedNumberOfEvents)5465     private boolean waitForRequestIsSatelliteProvisionedResult(int expectedNumberOfEvents) {
5466         for (int i = 0; i < expectedNumberOfEvents; i++) {
5467             try {
5468                 if (!mIsSatelliteProvisionedSemaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)) {
5469                     loge("Timeout to receive requestIsSatelliteProvisioned() callback");
5470                     return false;
5471                 }
5472             } catch (Exception ex) {
5473                 loge("waitForRequestIsSatelliteProvisionedResult: Got exception=" + ex);
5474                 return false;
5475             }
5476         }
5477         return true;
5478     }
5479 
waitForRequestSatelliteCapabilitiesResult(int expectedNumberOfEvents)5480     private boolean waitForRequestSatelliteCapabilitiesResult(int expectedNumberOfEvents) {
5481         for (int i = 0; i < expectedNumberOfEvents; i++) {
5482             try {
5483                 if (!mSatelliteCapabilitiesSemaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)) {
5484                     loge("Timeout to receive requestSatelliteCapabilities() callback");
5485                     return false;
5486                 }
5487             } catch (Exception ex) {
5488                 loge("waitForRequestSatelliteCapabilitiesResult: Got exception=" + ex);
5489                 return false;
5490             }
5491         }
5492         return true;
5493     }
5494 
waitForRequestIsDemoModeEnabledResult(int expectedNumberOfEvents)5495     private boolean waitForRequestIsDemoModeEnabledResult(int expectedNumberOfEvents) {
5496         for (int i = 0; i < expectedNumberOfEvents; i++) {
5497             try {
5498                 if (!mIsDemoModeEnabledSemaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)) {
5499                     loge("Timeout to receive requestIsDemoModeEnabled() callback");
5500                     return false;
5501                 }
5502             } catch (Exception ex) {
5503                 loge("waitForRequestIsDemoModeEnabled: Got exception=" + ex);
5504                 return false;
5505             }
5506         }
5507         return true;
5508     }
5509 
waitForRequestNtnSignalStrengthResult(int expectedNumberOfEvents)5510     private boolean waitForRequestNtnSignalStrengthResult(int expectedNumberOfEvents) {
5511         for (int i = 0; i < expectedNumberOfEvents; i++) {
5512             try {
5513                 if (!mRequestNtnSignalStrengthSemaphore.tryAcquire(TIMEOUT,
5514                         TimeUnit.MILLISECONDS)) {
5515                     loge("Timeout to receive requestNtnSignalStrength() callback");
5516                     return false;
5517                 }
5518             } catch (Exception ex) {
5519                 loge("requestNtnSignalStrength: Got exception=" + ex);
5520                 return false;
5521             }
5522         }
5523         return true;
5524     }
5525 
waitForIIntegerConsumerResult(int expectedNumberOfEvents)5526     private boolean waitForIIntegerConsumerResult(int expectedNumberOfEvents) {
5527         for (int i = 0; i < expectedNumberOfEvents; i++) {
5528             try {
5529                 if (!mIIntegerConsumerSemaphore.tryAcquire(TIMEOUT, TimeUnit.MILLISECONDS)) {
5530                     loge("Timeout to receive IIntegerConsumer() callback");
5531                     return false;
5532                 }
5533             } catch (Exception ex) {
5534                 loge("waitForIIntegerConsumerResult: Got exception=" + ex);
5535                 return false;
5536             }
5537         }
5538         return true;
5539     }
5540 
waitForRequestUpdateSystemSelectionChannelResult(int expectedNumberOfEvents)5541     private boolean waitForRequestUpdateSystemSelectionChannelResult(int expectedNumberOfEvents) {
5542         for (int i = 0; i < expectedNumberOfEvents; i++) {
5543             try {
5544                 if (!mSystemSelectionChannelUpdatedSemaphore.tryAcquire(TIMEOUT,
5545                         TimeUnit.MILLISECONDS)) {
5546                     logd("Timeout to receive "
5547                             + "updateSystemSelectionChannel()"
5548                             + " callback");
5549                     return false;
5550                 }
5551             } catch (Exception ex) {
5552                 logd("updateSystemSelectionChannel: Got exception=" + ex);
5553                 return false;
5554             }
5555         }
5556         return true;
5557     }
5558 
verifySatelliteSupported(boolean supported, int expectedErrorCode)5559     private void verifySatelliteSupported(boolean supported, int expectedErrorCode) {
5560         mSatelliteSupportSemaphore.drainPermits();
5561         mSatelliteControllerUT.requestIsSatelliteSupported(mSatelliteSupportReceiver);
5562         processAllMessages();
5563         assertTrue(waitForRequestIsSatelliteSupportedResult(1));
5564         assertEquals(expectedErrorCode, mQueriedSatelliteSupportedResultCode);
5565         assertEquals(supported, mQueriedSatelliteSupported);
5566     }
5567 
verifySatelliteSupported(TestSatelliteController satelliteController, boolean supported, int expectedErrorCode)5568     private void verifySatelliteSupported(TestSatelliteController satelliteController,
5569             boolean supported, int expectedErrorCode) {
5570         mSatelliteSupportSemaphore.drainPermits();
5571         satelliteController.requestIsSatelliteSupported(mSatelliteSupportReceiver);
5572         processAllMessages();
5573         assertTrue(waitForRequestIsSatelliteSupportedResult(1));
5574         assertEquals(expectedErrorCode, mQueriedSatelliteSupportedResultCode);
5575         assertEquals(supported, mQueriedSatelliteSupported);
5576     }
5577 
verifySatelliteEnabled(boolean enabled, int expectedErrorCode)5578     private void verifySatelliteEnabled(boolean enabled, int expectedErrorCode) {
5579         mIsSatelliteEnabledSemaphore.drainPermits();
5580         mSatelliteControllerUT.requestIsSatelliteEnabled(mIsSatelliteEnabledReceiver);
5581         processAllMessages();
5582         assertTrue(waitForRequestIsSatelliteEnabledResult(1));
5583         assertEquals(expectedErrorCode, mQueriedIsSatelliteEnabledResultCode);
5584         assertEquals(enabled, mQueriedIsSatelliteEnabled);
5585     }
5586 
verifySatelliteProvisioned(boolean provisioned, int expectedErrorCode)5587     private void verifySatelliteProvisioned(boolean provisioned, int expectedErrorCode) {
5588         mIsSatelliteProvisionedSemaphore.drainPermits();
5589         mSatelliteControllerUT.requestIsSatelliteProvisioned(mIsSatelliteProvisionedReceiver);
5590         processAllMessages();
5591         assertTrue(waitForRequestIsSatelliteProvisionedResult(1));
5592         assertEquals(expectedErrorCode, mQueriedIsSatelliteProvisionedResultCode);
5593         assertEquals(provisioned, mQueriedIsSatelliteProvisioned);
5594     }
5595 
verifyRequestNtnSignalStrength( @tnSignalStrength.NtnSignalStrengthLevel int signalStrengthLevel, int expectedErrorCode)5596     private void verifyRequestNtnSignalStrength(
5597             @NtnSignalStrength.NtnSignalStrengthLevel int signalStrengthLevel,
5598             int expectedErrorCode) {
5599         mRequestNtnSignalStrengthSemaphore.drainPermits();
5600         mSatelliteControllerUT.requestNtnSignalStrength(mRequestNtnSignalStrengthReceiver);
5601         processAllMessages();
5602         assertTrue(waitForRequestNtnSignalStrengthResult(1));
5603         assertEquals(expectedErrorCode, mQueriedNtnSignalStrengthResultCode);
5604         assertEquals(signalStrengthLevel, mQueriedNtnSignalStrengthLevel);
5605     }
5606 
setProvisionedState(@ullable Boolean provisioned)5607     private void setProvisionedState(@Nullable Boolean provisioned) {
5608         mSatelliteControllerUT.setSatelliteProvisioned(provisioned);
5609     }
5610 
sendSatelliteModemStateChangedEvent(int state, Throwable exception)5611     private void sendSatelliteModemStateChangedEvent(int state, Throwable exception) {
5612         Message msg = mSatelliteControllerUT.obtainMessage(
5613                 28 /* EVENT_SATELLITE_MODEM_STATE_CHANGED */);
5614         msg.obj = new AsyncResult(null, state, exception);
5615         msg.sendToTarget();
5616     }
5617 
sendNtnSignalStrengthChangedEvent( @tnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel, Throwable exception)5618     private void sendNtnSignalStrengthChangedEvent(
5619             @NtnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel,
5620             Throwable exception) {
5621         Message msg = mSatelliteControllerUT.obtainMessage(
5622                 34 /* EVENT_NTN_SIGNAL_STRENGTH_CHANGED */);
5623         msg.obj = new AsyncResult(null, new NtnSignalStrength(ntnSignalStrengthLevel),
5624                 exception);
5625         msg.sendToTarget();
5626     }
5627 
sendSignalStrengthChangedEvent(int phoneId)5628     private void sendSignalStrengthChangedEvent(int phoneId) {
5629         Message msg = mSatelliteControllerUT.obtainMessage(
5630                 57 /* EVENT_SIGNAL_STRENGTH_CHANGED */);
5631         msg.obj = new AsyncResult(phoneId, null, null);
5632         msg.sendToTarget();
5633     }
5634 
sendCmdStartSendingNtnSignalStrengthChangedEvent(boolean shouldReport)5635     private void sendCmdStartSendingNtnSignalStrengthChangedEvent(boolean shouldReport) {
5636         Message msg = mSatelliteControllerUT.obtainMessage(
5637                 35 /* CMD_UPDATE_NTN_SIGNAL_STRENGTH_REPORTING */);
5638         msg.obj = new AsyncResult(null, shouldReport, null);
5639         msg.sendToTarget();
5640     }
5641 
sendStartSendingNtnSignalStrengthChangedEvent( @tnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel, Throwable exception)5642     private void sendStartSendingNtnSignalStrengthChangedEvent(
5643             @NtnSignalStrength.NtnSignalStrengthLevel int ntnSignalStrengthLevel,
5644             Throwable exception) {
5645         Message msg = mSatelliteControllerUT.obtainMessage(
5646                 36 /* EVENT_UPDATE_NTN_SIGNAL_STRENGTH_REPORTING_DONE */);
5647         msg.obj = new AsyncResult(null, new NtnSignalStrength(ntnSignalStrengthLevel),
5648                 exception);
5649         msg.sendToTarget();
5650     }
5651 
sendServiceStateChangedEvent()5652     private void sendServiceStateChangedEvent() {
5653         mSatelliteControllerUT.obtainMessage(37 /* EVENT_SERVICE_STATE_CHANGED */).sendToTarget();
5654     }
5655 
sendSatelliteCapabilitiesChangedEvent(SatelliteCapabilities capabilities, Throwable exception)5656     private void sendSatelliteCapabilitiesChangedEvent(SatelliteCapabilities capabilities,
5657             Throwable exception) {
5658         Message msg = mSatelliteControllerUT.obtainMessage(
5659                 38 /* EVENT_SATELLITE_CAPABILITIES_CHANGED */);
5660         msg.obj = new AsyncResult(null, capabilities, exception);
5661         msg.sendToTarget();
5662     }
5663 
sendSatelliteSupportedStateChangedEvent(boolean supported, Throwable exception)5664     private void sendSatelliteSupportedStateChangedEvent(boolean supported, Throwable exception) {
5665         Message msg = mSatelliteControllerUT.obtainMessage(
5666                 41 /* EVENT_SATELLITE_SUPPORTED_STATE_CHANGED */);
5667         msg.obj = new AsyncResult(null, supported, exception);
5668         msg.sendToTarget();
5669     }
5670 
sendSatelliteRegistrationFailureEvent(int errorCode, Throwable exception)5671     private void sendSatelliteRegistrationFailureEvent(int errorCode, Throwable exception) {
5672         Message msg = mSatelliteControllerUT.obtainMessage(
5673                 54 /* EVENT_SATELLITE_REGISTRATION_FAILURE */);
5674         msg.obj = new AsyncResult(null, errorCode, exception);
5675         msg.sendToTarget();
5676     }
5677 
sendTerrestrialNetworkAvailableChangedEvent(boolean isAvailable, Throwable exception)5678     private void sendTerrestrialNetworkAvailableChangedEvent(boolean isAvailable,
5679             Throwable exception) {
5680         Message msg = mSatelliteControllerUT.obtainMessage(
5681                 55 /* EVENT_TERRESTRIAL_NETWORK_AVAILABLE_CHANGED */);
5682         msg.obj = new AsyncResult(null, isAvailable, exception);
5683         msg.sendToTarget();
5684     }
5685 
sendSelectedNbIotSatelliteSubscriptionChangedEvent(int selectedSubId, Throwable exception)5686     private void sendSelectedNbIotSatelliteSubscriptionChangedEvent(int selectedSubId,
5687             Throwable exception) {
5688         Message msg = mSatelliteControllerUT.obtainMessage(
5689                 60 /* EVENT_SELECTED_NB_IOT_SATELLITE_SUBSCRIPTION_CHANGED */);
5690         msg.obj = new AsyncResult(null, selectedSubId, exception);
5691         msg.sendToTarget();
5692     }
5693 
sendCmdEvaluateCarrierRoamingNtnEligibilityChange()5694     private void sendCmdEvaluateCarrierRoamingNtnEligibilityChange() {
5695         mSatelliteControllerUT.obtainMessage(
5696                 61 /* CMD_EVALUATE_CARRIER_ROAMING_NTN_ELIGIBILITY_CHANGE */).sendToTarget();
5697     }
5698 
sendCmdGetSatelliteEnabledForCarrier(Phone phone)5699     private void sendCmdGetSatelliteEnabledForCarrier(Phone phone) {
5700         SatelliteController.SatelliteControllerHandlerRequest request =
5701                 new SatelliteController.SatelliteControllerHandlerRequest(null, phone);
5702         Message msg = mSatelliteControllerUT.obtainMessage(
5703                 64 /* CMD_GET_SATELLITE_ENABLED_FOR_CARRIER */, request);
5704         msg.sendToTarget();
5705     }
5706 
sendEventGetSatelliteEnabledForCarrierDone(int subId, Boolean result, Throwable exception)5707     private void sendEventGetSatelliteEnabledForCarrierDone(int subId, Boolean result,
5708             Throwable exception) {
5709         Message msg = mSatelliteControllerUT.obtainMessage(
5710                 65 /* EVENT_GET_SATELLITE_ENABLED_FOR_CARRIER_DONE */, subId);
5711         msg.obj = new AsyncResult(subId, result, exception);
5712         msg.sendToTarget();
5713     }
5714 
setRadioPower(boolean on)5715     private void setRadioPower(boolean on) {
5716         mSimulatedCommands.setRadioPower(on, false, false, null);
5717     }
5718 
verifyRegisterForNtnSignalStrengthChanged(int subId, INtnSignalStrengthCallback callback, int expectedError)5719     private void verifyRegisterForNtnSignalStrengthChanged(int subId,
5720             INtnSignalStrengthCallback callback, int expectedError) {
5721         if (expectedError == SATELLITE_RESULT_SUCCESS) {
5722             try {
5723                 mSatelliteControllerUT.registerForNtnSignalStrengthChanged(callback);
5724             } catch (RemoteException ex) {
5725                 throw new AssertionError();
5726             }
5727         } else {
5728             RemoteException ex = assertThrows(RemoteException.class,
5729                     () -> mSatelliteControllerUT.registerForNtnSignalStrengthChanged(callback));
5730             assertTrue("The cause is not IllegalStateException",
5731                     ex.getCause() instanceof IllegalStateException);
5732         }
5733     }
5734 
provisionSatelliteService()5735     private void provisionSatelliteService() {
5736         String mText = "This is test provision data.";
5737         byte[] testProvisionData = mText.getBytes();
5738         ICancellationSignal cancelRemote;
5739         mIIntegerConsumerResults.clear();
5740         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
5741         setUpResponseForRequestIsSatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
5742         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
5743         verifySatelliteProvisioned(false, SATELLITE_RESULT_SUCCESS);
5744 
5745         try {
5746             setSatelliteSubscriberTesting(true);
5747         } catch (Exception ex) {
5748             fail("provisionSatelliteService.setSatelliteSubscriberTesting: ex=" + ex);
5749         }
5750         doReturn(true).when(mMockSubscriptionManagerService).isSatelliteProvisionedForNonIpDatagram(
5751                 anyInt());
5752 
5753         cancelRemote = mSatelliteControllerUT.provisionSatelliteService(
5754                 TEST_SATELLITE_TOKEN,
5755                 testProvisionData, mIIntegerConsumer);
5756         processAllMessages();
5757         assertTrue(waitForIIntegerConsumerResult(1));
5758         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
5759         assertNotNull(cancelRemote);
5760         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
5761     }
5762 
deprovisionSatelliteService()5763     private void deprovisionSatelliteService() {
5764         mIIntegerConsumerResults.clear();
5765         mSatelliteControllerUT.deprovisionSatelliteService(
5766                 TEST_SATELLITE_TOKEN, mIIntegerConsumer);
5767         processAllMessages();
5768         assertTrue(waitForIIntegerConsumerResult(1));
5769         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
5770     }
5771 
loge(String message)5772     private static void loge(String message) {
5773         Rlog.e(TAG, message);
5774     }
5775 
5776     private static class TestSharedPreferences
5777             implements SharedPreferences, SharedPreferences.Editor {
5778         private HashMap<String, Object> mValues = new HashMap<String, Object>();
5779 
getValueCount()5780         public int getValueCount() {
5781             return mValues.size();
5782         }
5783 
5784         @Override
edit()5785         public Editor edit() {
5786             return this;
5787         }
5788 
5789         @Override
contains(String key)5790         public boolean contains(String key) {
5791             return mValues.containsKey(key);
5792         }
5793 
5794         @Override
getAll()5795         public Map<String, ?> getAll() {
5796             return new HashMap<String, Object>(mValues);
5797         }
5798 
5799         @Override
getBoolean(String key, boolean defValue)5800         public boolean getBoolean(String key, boolean defValue) {
5801             if (mValues.containsKey(key)) {
5802                 return ((Boolean) mValues.get(key)).booleanValue();
5803             }
5804             return defValue;
5805         }
5806 
5807         @Override
getFloat(String key, float defValue)5808         public float getFloat(String key, float defValue) {
5809             if (mValues.containsKey(key)) {
5810                 return ((Float) mValues.get(key)).floatValue();
5811             }
5812             return defValue;
5813         }
5814 
5815         @Override
getInt(String key, int defValue)5816         public int getInt(String key, int defValue) {
5817             if (mValues.containsKey(key)) {
5818                 return ((Integer) mValues.get(key)).intValue();
5819             }
5820             return defValue;
5821         }
5822 
5823         @Override
getLong(String key, long defValue)5824         public long getLong(String key, long defValue) {
5825             if (mValues.containsKey(key)) {
5826                 return ((Long) mValues.get(key)).longValue();
5827             }
5828             return defValue;
5829         }
5830 
5831         @Override
getString(String key, String defValue)5832         public String getString(String key, String defValue) {
5833             if (mValues.containsKey(key)) return (String) mValues.get(key);
5834             else return defValue;
5835         }
5836 
5837         @SuppressWarnings("unchecked")
5838         @Override
getStringSet(String key, Set<String> defValues)5839         public Set<String> getStringSet(String key, Set<String> defValues) {
5840             if (mValues.containsKey(key)) {
5841                 return (Set<String>) mValues.get(key);
5842             }
5843             return defValues;
5844         }
5845 
5846         @Override
registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener)5847         public void registerOnSharedPreferenceChangeListener(
5848                 OnSharedPreferenceChangeListener listener) {
5849             throw new UnsupportedOperationException();
5850         }
5851 
5852         @Override
unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener)5853         public void unregisterOnSharedPreferenceChangeListener(
5854                 OnSharedPreferenceChangeListener listener) {
5855             throw new UnsupportedOperationException();
5856         }
5857 
5858         @Override
putBoolean(String key, boolean value)5859         public Editor putBoolean(String key, boolean value) {
5860             mValues.put(key, Boolean.valueOf(value));
5861             return this;
5862         }
5863 
5864         @Override
putFloat(String key, float value)5865         public Editor putFloat(String key, float value) {
5866             mValues.put(key, value);
5867             return this;
5868         }
5869 
5870         @Override
putInt(String key, int value)5871         public Editor putInt(String key, int value) {
5872             mValues.put(key, value);
5873             return this;
5874         }
5875 
5876         @Override
putLong(String key, long value)5877         public Editor putLong(String key, long value) {
5878             mValues.put(key, value);
5879             return this;
5880         }
5881 
5882         @Override
putString(String key, String value)5883         public Editor putString(String key, String value) {
5884             mValues.put(key, value);
5885             return this;
5886         }
5887 
5888         @Override
putStringSet(String key, Set<String> values)5889         public Editor putStringSet(String key, Set<String> values) {
5890             mValues.put(key, values);
5891             return this;
5892         }
5893 
5894         @Override
remove(String key)5895         public Editor remove(String key) {
5896             mValues.remove(key);
5897             return this;
5898         }
5899 
5900         @Override
clear()5901         public Editor clear() {
5902             mValues.clear();
5903             return this;
5904         }
5905 
5906         @Override
commit()5907         public boolean commit() {
5908             return true;
5909         }
5910 
5911         @Override
apply()5912         public void apply() {
5913             commit();
5914         }
5915     }
5916 
5917     public class TestSatelliteController extends SatelliteController {
5918         public boolean setSettingsKeyForSatelliteModeCalled = false;
5919         public boolean allRadiosDisabled = true;
5920         public long elapsedRealtime = 0;
5921         public int satelliteModeSettingValue = SATELLITE_MODE_ENABLED_FALSE;
5922         public boolean setSettingsKeyToAllowDeviceRotationCalled = false;
5923         public OutcomeReceiver<Boolean, SatelliteException> isSatelliteAllowedCallback = null;
5924         public static boolean isApplicationUpdated;
5925         public String packageName = "com.example.app";
5926         public boolean isSatelliteBeingDisabled = false;
5927         public boolean mIsApplicationSupportsP2P = false;
5928         public int selectedSatelliteSubId = -1;
5929         public boolean isSatelliteProvisioned;
5930 
5931         private boolean callOnlySuperMethod = false;
5932         public boolean isSatelliteEnabledOrBeingEnabled = false;
5933 
5934         private boolean mLocationServiceEnabled = true;
5935 
TestSatelliteController( Context context, Looper looper, @NonNull FeatureFlags featureFlags)5936         public TestSatelliteController(
5937                 Context context, Looper looper, @NonNull FeatureFlags featureFlags) {
5938             super(context, looper, featureFlags);
5939             logd("Constructing TestSatelliteController");
5940             isApplicationUpdated = false;
5941         }
5942 
5943         @Override
initializeSatelliteModeRadios()5944         protected void initializeSatelliteModeRadios() {
5945             logd("initializeSatelliteModeRadios");
5946         }
5947 
5948         @Override
setSettingsKeyForSatelliteMode(int val)5949         protected void setSettingsKeyForSatelliteMode(int val) {
5950             logd("setSettingsKeyForSatelliteMode: val=" + val);
5951             satelliteModeSettingValue = val;
5952             setSettingsKeyForSatelliteModeCalled = true;
5953         }
5954 
5955         @Override
setSettingsKeyToAllowDeviceRotation(int val)5956         protected void setSettingsKeyToAllowDeviceRotation(int val) {
5957             logd("setSettingsKeyToAllowDeviceRotation: val=" + val);
5958             setSettingsKeyToAllowDeviceRotationCalled = true;
5959         }
5960 
5961         @Override
areAllRadiosDisabled()5962         protected boolean areAllRadiosDisabled() {
5963             logd("areAllRadiosDisabled: " + allRadiosDisabled);
5964             return allRadiosDisabled;
5965         }
5966 
5967         @Override
getSupportedNtnRadioTechnology()5968         protected int getSupportedNtnRadioTechnology() {
5969             int ntRadioTechnology = super.getSupportedNtnRadioTechnology();
5970             logd("getCurrentNtnRadioTechnology: val=" + ntRadioTechnology);
5971             return ntRadioTechnology;
5972         }
5973 
5974         @Override
getElapsedRealtime()5975         protected long getElapsedRealtime() {
5976             return elapsedRealtime;
5977         }
5978 
5979         @Override
registerForSatelliteCommunicationAccessStateChanged()5980         protected void registerForSatelliteCommunicationAccessStateChanged() {
5981             logd("registerForSatelliteCommunicationAccessStateChanged");
5982         }
5983 
setSatelliteSessionController(SatelliteSessionController satelliteSessionController)5984         void setSatelliteSessionController(SatelliteSessionController satelliteSessionController) {
5985             mSatelliteSessionController = satelliteSessionController;
5986         }
5987 
5988         @Override
setSatellitePhone(int subId)5989         protected void setSatellitePhone(int subId) {
5990             logd("setSatellitePhone");
5991             synchronized (mSatellitePhoneLock) {
5992                 mSatellitePhone = mPhone;
5993             }
5994         }
5995 
5996         @Override
setSelectedSatelliteSubId(int subId)5997         protected void setSelectedSatelliteSubId(int subId) {
5998             logd("setSelectedSatelliteSubId: subId=" + subId);
5999             synchronized (mSatelliteTokenProvisionedLock) {
6000                 mSelectedSatelliteSubId = subId;
6001             }
6002         }
6003 
6004         @Override
isSubscriptionProvisioned(int subId)6005         protected boolean isSubscriptionProvisioned(int subId) {
6006             return isSatelliteProvisioned;
6007         }
6008 
6009         @Override
getSupportedDeviceStates()6010         protected List<DeviceState> getSupportedDeviceStates() {
6011             return List.of(new DeviceState(new DeviceState.Configuration.Builder(0 /* identifier */,
6012                     "DEFAULT" /* name */).build()));
6013         }
6014 
6015         @Override
isSatelliteBeingDisabled()6016         public boolean isSatelliteBeingDisabled() {
6017             return isSatelliteBeingDisabled;
6018         }
6019 
6020         @Override
isSatelliteEnabledOrBeingEnabled()6021         public boolean isSatelliteEnabledOrBeingEnabled() {
6022             return isSatelliteEnabledOrBeingEnabled;
6023         }
6024 
getConfigSatelliteGatewayServicePackage()6025         protected String getConfigSatelliteGatewayServicePackage() {
6026             String packageName = "com.example.app";
6027             return packageName;
6028         }
6029 
6030         @Override
handleCarrierRoamingNtnAvailableServicesChanged(int subId)6031         protected void handleCarrierRoamingNtnAvailableServicesChanged(int subId) {
6032             if (callOnlySuperMethod) {
6033                 super.handleCarrierRoamingNtnAvailableServicesChanged(subId);
6034             } else {
6035                 isApplicationUpdated = true;
6036             }
6037         }
6038 
6039         @Override
isApplicationSupportsP2P(String packageName)6040         public boolean isApplicationSupportsP2P(String packageName) {
6041             return mIsApplicationSupportsP2P;
6042         }
6043 
6044         @Override
getSupportedServicesOnCarrierRoamingNtn(int subId)6045         public int[] getSupportedServicesOnCarrierRoamingNtn(int subId) {
6046             if (callOnlySuperMethod) {
6047                 return super.getSupportedServicesOnCarrierRoamingNtn(subId);
6048             }
6049             return new int[]{3, 5};
6050         }
6051 
6052         @Override
getSelectedSatelliteSubId()6053         public int getSelectedSatelliteSubId() {
6054             return selectedSatelliteSubId;
6055         }
6056 
6057         @Override
isLocationServiceEnabled()6058         protected boolean isLocationServiceEnabled() {
6059             return mLocationServiceEnabled;
6060         }
6061 
6062         @Override
isSatelliteAvailableAtCurrentLocation(@ullable SubscriptionInfo info)6063         protected boolean isSatelliteAvailableAtCurrentLocation(@Nullable SubscriptionInfo info) {
6064             return super.isSatelliteAvailableAtCurrentLocation(info);
6065         }
6066 
setSatelliteProvisioned(@ullable Boolean isProvisioned)6067         void setSatelliteProvisioned(@Nullable Boolean isProvisioned) {
6068             synchronized (mDeviceProvisionLock) {
6069                 mIsDeviceProvisioned = isProvisioned;
6070             }
6071         }
6072 
setIsSatelliteSupported(@ullable Boolean isSatelliteSupported)6073         void setIsSatelliteSupported(@Nullable Boolean isSatelliteSupported) {
6074             synchronized (mIsSatelliteSupportedLock) {
6075                 mIsSatelliteSupported = isSatelliteSupported;
6076             }
6077         }
6078 
6079         @Override
getAllPlmnSet()6080         protected Set<String> getAllPlmnSet() {
6081             return super.getAllPlmnSet();
6082         }
6083 
isRadioOn()6084         public boolean isRadioOn() {
6085             synchronized (mIsRadioOnLock) {
6086                 return mIsRadioOn;
6087             }
6088         }
6089 
isRadioOffRequested()6090         public boolean isRadioOffRequested() {
6091             synchronized (mIsRadioOnLock) {
6092                 return mRadioOffRequested;
6093             }
6094         }
6095 
isWaitForCellularModemOffTimerStarted()6096         public boolean isWaitForCellularModemOffTimerStarted() {
6097             return hasMessages(EVENT_WAIT_FOR_CELLULAR_MODEM_OFF_TIMED_OUT);
6098         }
6099 
subscriberIdPerSub()6100         public Map<String, Integer> subscriberIdPerSub() {
6101             synchronized (mSatelliteTokenProvisionedLock) {
6102                 return mSubscriberIdPerSub;
6103             }
6104         }
6105 
subsInfoListPerPriority()6106         public Map<Integer, List<SubscriptionInfo>> subsInfoListPerPriority() {
6107             synchronized (mSatelliteTokenProvisionedLock) {
6108                 return mSubsInfoListPerPriority;
6109             }
6110         }
6111 
evaluateESOSProfilesPrioritizationTest()6112         public void evaluateESOSProfilesPrioritizationTest() {
6113             evaluateESOSProfilesPrioritization();
6114         }
6115 
isCarrierSatelliteHigherPriorityTest(SubscriptionInfo info)6116         public boolean isCarrierSatelliteHigherPriorityTest(SubscriptionInfo info) {
6117             return isCarrierSatelliteHigherPriority(info);
6118         }
6119 
getStringFromOverlayConfigTest(int resourceId)6120         public String getStringFromOverlayConfigTest(int resourceId) {
6121             return getStringFromOverlayConfig(resourceId);
6122         }
6123 
isAnyWaitForSatelliteEnablingResponseTimerStarted()6124         public boolean isAnyWaitForSatelliteEnablingResponseTimerStarted() {
6125             return hasMessages(EVENT_WAIT_FOR_SATELLITE_ENABLING_RESPONSE_TIMED_OUT);
6126         }
6127 
getResultReceiverTotalCount()6128         public int getResultReceiverTotalCount() {
6129             synchronized (mResultReceiverTotalCountLock) {
6130                 return mResultReceiverTotalCount;
6131             }
6132         }
6133 
getResultReceiverCountPerMethodMap()6134         public HashMap<String, Integer> getResultReceiverCountPerMethodMap() {
6135             synchronized (mResultReceiverTotalCountLock) {
6136                 return mResultReceiverCountPerMethodMap;
6137             }
6138         }
6139 
setIsSatelliteAllowedState(boolean isAllowed)6140         public void setIsSatelliteAllowedState(boolean isAllowed) {
6141             synchronized(mSatelliteAccessConfigLock) {
6142                 mSatelliteAccessAllowed = isAllowed;
6143             }
6144         }
6145 
setCallOnlySuperMethod()6146         public void setCallOnlySuperMethod() {
6147             callOnlySuperMethod = true;
6148         }
6149 
setLocationServiceEnabled(boolean locationServiceEnabled)6150         public void  setLocationServiceEnabled(boolean locationServiceEnabled) {
6151             mLocationServiceEnabled = locationServiceEnabled;
6152         }
6153 
getLocationReceiver()6154         public BroadcastReceiver getLocationReceiver() {
6155             return mLocationServiceStateChangedReceiver;
6156         }
6157     }
6158 
6159     @Test
testLoggingCodeForResultReceiverCount()6160     public void testLoggingCodeForResultReceiverCount() throws Exception {
6161         final String callerSC =  "SC:ResultReceiver";
6162         final String callerSAC =  "SAC:ResultReceiver";
6163 
6164         doReturn(false).when(mFeatureFlags).carrierRoamingNbIotNtn();
6165 
6166         mSatelliteControllerUT.incrementResultReceiverCount(callerSC);
6167         assertEquals(0, mSatelliteControllerUT.getResultReceiverTotalCount());
6168         mSatelliteControllerUT.decrementResultReceiverCount(callerSC);
6169         assertEquals(0, mSatelliteControllerUT.getResultReceiverTotalCount());
6170 
6171         doReturn(true).when(mFeatureFlags).carrierRoamingNbIotNtn();
6172 
6173         mSatelliteControllerUT.incrementResultReceiverCount(callerSC);
6174         assertEquals(1, mSatelliteControllerUT.getResultReceiverTotalCount());
6175         assertEquals(1, mSatelliteControllerUT.getResultReceiverCountPerMethodMap().size());
6176         assertEquals(1, (int) Optional.ofNullable(mSatelliteControllerUT
6177                 .getResultReceiverCountPerMethodMap().get(callerSC)).orElse(0));
6178         assertEquals(0, (int) Optional.ofNullable(mSatelliteControllerUT
6179                 .getResultReceiverCountPerMethodMap().get(callerSAC)).orElse(0));
6180 
6181         mSatelliteControllerUT.incrementResultReceiverCount(callerSC);
6182         assertEquals(2, mSatelliteControllerUT.getResultReceiverTotalCount());
6183         assertEquals(1, mSatelliteControllerUT.getResultReceiverCountPerMethodMap().size());
6184         assertEquals(2, (int) Optional.ofNullable(mSatelliteControllerUT
6185                 .getResultReceiverCountPerMethodMap().get(callerSC)).orElse(0));
6186         assertEquals(0, (int) Optional.ofNullable(mSatelliteControllerUT
6187                 .getResultReceiverCountPerMethodMap().get(callerSAC)).orElse(0));
6188 
6189         mSatelliteControllerUT.incrementResultReceiverCount(callerSAC);
6190         assertEquals(3, mSatelliteControllerUT.getResultReceiverTotalCount());
6191         assertEquals(2, mSatelliteControllerUT.getResultReceiverCountPerMethodMap().size());
6192         assertEquals(2, (int) Optional.ofNullable(mSatelliteControllerUT
6193                 .getResultReceiverCountPerMethodMap().get(callerSC)).orElse(0));
6194         assertEquals(1, (int) Optional.ofNullable(mSatelliteControllerUT
6195                 .getResultReceiverCountPerMethodMap().get(callerSAC)).orElse(0));
6196 
6197         mSatelliteControllerUT.decrementResultReceiverCount(callerSC);
6198         assertEquals(2, mSatelliteControllerUT.getResultReceiverTotalCount());
6199         assertEquals(2, mSatelliteControllerUT.getResultReceiverCountPerMethodMap().size());
6200         assertEquals(1, (int) Optional.ofNullable(mSatelliteControllerUT
6201                 .getResultReceiverCountPerMethodMap().get(callerSC)).orElse(0));
6202         assertEquals(1, (int) Optional.ofNullable(mSatelliteControllerUT
6203                 .getResultReceiverCountPerMethodMap().get(callerSAC)).orElse(0));
6204 
6205         mSatelliteControllerUT.decrementResultReceiverCount(callerSC);
6206         assertEquals(1, mSatelliteControllerUT.getResultReceiverTotalCount());
6207         assertEquals(2, mSatelliteControllerUT.getResultReceiverCountPerMethodMap().size());
6208         assertEquals(0, (int) Optional.ofNullable(mSatelliteControllerUT
6209                 .getResultReceiverCountPerMethodMap().get(callerSC)).orElse(0));
6210         assertEquals(1, (int) Optional.ofNullable(mSatelliteControllerUT
6211                 .getResultReceiverCountPerMethodMap().get(callerSAC)).orElse(0));
6212 
6213         mSatelliteControllerUT.decrementResultReceiverCount(callerSAC);
6214         assertEquals(0, mSatelliteControllerUT.getResultReceiverTotalCount());
6215         assertEquals(2, mSatelliteControllerUT.getResultReceiverCountPerMethodMap().size());
6216         assertEquals(0, (int) Optional.ofNullable(mSatelliteControllerUT
6217                 .getResultReceiverCountPerMethodMap().get(callerSC)).orElse(0));
6218         assertEquals(0, (int) Optional.ofNullable(mSatelliteControllerUT
6219                 .getResultReceiverCountPerMethodMap().get(callerSAC)).orElse(0));
6220     }
6221 
6222     @Test
testSetNtnSmsSupportedByMessagesApp()6223     public void testSetNtnSmsSupportedByMessagesApp() {
6224         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
6225         mSatelliteControllerUT.setNtnSmsSupportedByMessagesApp(true);
6226         assertTrue(mSharedPreferences.getBoolean(
6227                 SatelliteController.NTN_SMS_SUPPORTED_BY_MESSAGES_APP_KEY, false));
6228     }
6229 
6230     private static class TestSubscriptionManager {
6231         public Map<Integer, Boolean> mSatelliteProvisionedForNonIpDatagram = new HashMap<>();
6232 
resetProvisionMapForNonIpDatagram()6233         public void resetProvisionMapForNonIpDatagram() {
6234             mSatelliteProvisionedForNonIpDatagram.clear();
6235         }
6236 
setIsSatelliteProvisionedForNonIpDatagram(int subId, boolean provisioned)6237         public void setIsSatelliteProvisionedForNonIpDatagram(int subId, boolean provisioned) {
6238             mSatelliteProvisionedForNonIpDatagram.put(subId, provisioned);
6239         }
6240 
isSatelliteProvisionedForNonIpDatagram(int subId)6241         public boolean isSatelliteProvisionedForNonIpDatagram(int subId) {
6242             Boolean isProvisioned = mSatelliteProvisionedForNonIpDatagram.get(subId);
6243             return isProvisioned != null ? isProvisioned : false;
6244         }
6245     }
6246 
6247     @Test
testGetSatelliteDataPlanForPlmn_WithEntitlement()6248     public void testGetSatelliteDataPlanForPlmn_WithEntitlement() throws Exception {
6249         logd("testGetSatelliteDataPlanForPlmn_WithEntitlement");
6250 
6251         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
6252                 mSatelliteControllerUT, new SparseArray<>());
6253         List<String> overlayConfigPlmnList = new ArrayList<>();
6254         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6255                 mSatelliteControllerUT, overlayConfigPlmnList);
6256         mCarrierConfigBundle.putBoolean(
6257                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6258         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6259                 true);
6260 
6261         List<String> entitlementPlmnList =
6262                 Arrays.stream(new String[]{"00101", "00102", "00103", "00104"})
6263                         .toList();
6264         List<String> barredPlmnList = new ArrayList<>();
6265         Map<String, Integer> dataPlanListMap = Map.of(
6266                 "00101", SATELLITE_DATA_PLAN_METERED,
6267                 "00103", SATELLITE_DATA_PLAN_UNMETERED);
6268         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6269                 entitlementPlmnList, barredPlmnList, dataPlanListMap, new HashMap<>(),
6270                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6271 
6272         int dataPlanForPlmn;
6273         dataPlanForPlmn = mSatelliteControllerUT.getSatelliteDataPlanForPlmn(SUB_ID, "00101");
6274         assertEquals(SATELLITE_DATA_PLAN_METERED, dataPlanForPlmn);
6275 
6276         dataPlanForPlmn = mSatelliteControllerUT.getSatelliteDataPlanForPlmn(SUB_ID, "00103");
6277         assertEquals(SATELLITE_DATA_PLAN_UNMETERED, dataPlanForPlmn);
6278     }
6279 
6280     @Test
testGetSatelliteDataPlanForPlmn_WithoutEntitlement()6281     public void testGetSatelliteDataPlanForPlmn_WithoutEntitlement() throws Exception {
6282         logd("testGetSatelliteDataPlanForPlmn_WithoutEntitlement");
6283 
6284         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
6285                 mSatelliteControllerUT, new SparseArray<>());
6286         List<String> overlayConfigPlmnList = new ArrayList<>();
6287         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6288                 mSatelliteControllerUT, overlayConfigPlmnList);
6289         mCarrierConfigBundle.putBoolean(
6290                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6291         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6292                 true);
6293 
6294         List<String> entitlementPlmnList =
6295                 Arrays.stream(new String[]{"00101", "00102", "00103", "00104"})
6296                         .toList();
6297         List<String> barredPlmnList = new ArrayList<>();
6298         Map<String, Integer> dataPlanListMap = new HashMap<>();
6299         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6300                 entitlementPlmnList, barredPlmnList, dataPlanListMap, new HashMap<>(),
6301                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6302 
6303         int dataPlanForPlmn = mSatelliteControllerUT.getSatelliteDataPlanForPlmn(SUB_ID, "00101");
6304         assertEquals(SATELLITE_DATA_PLAN_METERED, dataPlanForPlmn);
6305     }
6306 
6307     @Test
testSupportedSatelliteServices_WithoutDataEntitlement_WithNoDataServiceWithConfig()6308     public void testSupportedSatelliteServices_WithoutDataEntitlement_WithNoDataServiceWithConfig()
6309             throws Exception {
6310         logd("TestGetSupportedSatelliteServicesForPlmn_WithEntitlement");
6311 
6312         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
6313                 mSatelliteControllerUT, new SparseArray<>());
6314         List<String> overlayConfigPlmnList = new ArrayList<>();
6315         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6316                 mSatelliteControllerUT, overlayConfigPlmnList);
6317         mCarrierConfigBundle.putBoolean(
6318                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6319         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6320                 true);
6321         mCarrierConfigBundle.putInt(
6322                 CarrierConfigManager.KEY_SATELLITE_DATA_SUPPORT_MODE_INT,
6323                 SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED);
6324         PersistableBundle carrierSupportedSatelliteServicesPerProvider =
6325                 new PersistableBundle();
6326         List<String> carrierConfigPlmnList = List.of("00101", "00102", "00103");
6327         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6328                 carrierConfigPlmnList.get(0), new int[]{3, 6});
6329         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6330                 carrierConfigPlmnList.get(1), new int[]{3, 6});
6331         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6332                 carrierConfigPlmnList.get(2), new int[]{3, 6});
6333         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
6334                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
6335                 carrierSupportedSatelliteServicesPerProvider);
6336         invokeCarrierConfigChanged();
6337 
6338         List<String> entitlementPlmnList =
6339                 Arrays.stream(new String[]{"00101", "00102", "00103", "00104"})
6340                         .toList();
6341         List<String> barredPlmnList = new ArrayList<>();
6342         Map<String, List<Integer>> serviceTypeListMap = Map.of(
6343                 "00101", List.of(SERVICE_TYPE_SMS),
6344                 "00102", List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS),
6345                 "00103", List.of());
6346         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6347                 entitlementPlmnList, barredPlmnList, new HashMap<>(), serviceTypeListMap,
6348                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6349 
6350         List<Integer> allowedServiceForPlmn;
6351         allowedServiceForPlmn = mSatelliteControllerUT
6352                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00101");
6353         assertEquals(List.of(SERVICE_TYPE_SMS), allowedServiceForPlmn);
6354 
6355         allowedServiceForPlmn = mSatelliteControllerUT
6356                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00102");
6357         assertEquals(List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS), allowedServiceForPlmn);
6358 
6359         allowedServiceForPlmn = mSatelliteControllerUT
6360                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00103");
6361         assertEquals(List.of(SERVICE_TYPE_SMS, SERVICE_TYPE_MMS),
6362                 allowedServiceForPlmn);
6363     }
6364 
6365     @Test
testSupportedSatelliteServices_WithoutDataEntitlement_WithDataServiceConfig()6366     public void testSupportedSatelliteServices_WithoutDataEntitlement_WithDataServiceConfig()
6367             throws Exception {
6368         logd("TestGetSupportedSatelliteServicesForPlmn_WithEntitlement");
6369 
6370         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
6371                 mSatelliteControllerUT, new SparseArray<>());
6372         List<String> overlayConfigPlmnList = new ArrayList<>();
6373         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6374                 mSatelliteControllerUT, overlayConfigPlmnList);
6375         mCarrierConfigBundle.putBoolean(
6376                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6377         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6378                 true);
6379         mCarrierConfigBundle.putInt(
6380                 CarrierConfigManager.KEY_SATELLITE_DATA_SUPPORT_MODE_INT,
6381                 SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED);
6382         PersistableBundle carrierSupportedSatelliteServicesPerProvider =
6383                 new PersistableBundle();
6384         List<String> carrierConfigPlmnList = List.of("00101", "00102", "00103");
6385         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6386                 carrierConfigPlmnList.get(0), new int[]{2, 3, 6});
6387         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6388                 carrierConfigPlmnList.get(1), new int[]{2, 3, 6});
6389         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6390                 carrierConfigPlmnList.get(2), new int[]{2, 3});
6391         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
6392                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
6393                 carrierSupportedSatelliteServicesPerProvider);
6394         invokeCarrierConfigChanged();
6395 
6396         List<String> entitlementPlmnList =
6397                 Arrays.stream(new String[]{"00101", "00102", "00103", "00104"})
6398                         .toList();
6399         List<String> barredPlmnList = new ArrayList<>();
6400         Map<String, List<Integer>> serviceTypeListMap = Map.of(
6401                 "00101", List.of(SERVICE_TYPE_SMS),
6402                 "00102", List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS),
6403                 "00103", List.of());
6404         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6405                 entitlementPlmnList, barredPlmnList, new HashMap<>(), serviceTypeListMap,
6406                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6407 
6408         List<Integer> allowedServiceForPlmn;
6409         allowedServiceForPlmn = mSatelliteControllerUT
6410                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00101");
6411         assertEquals(List.of(SERVICE_TYPE_SMS, SERVICE_TYPE_DATA, SERVICE_TYPE_MMS),
6412                 allowedServiceForPlmn);
6413 
6414         allowedServiceForPlmn = mSatelliteControllerUT
6415                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00102");
6416         assertEquals(List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS, SERVICE_TYPE_DATA,
6417                         SERVICE_TYPE_MMS),
6418                 allowedServiceForPlmn);
6419 
6420         allowedServiceForPlmn = mSatelliteControllerUT
6421                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00103");
6422         assertEquals(List.of(SERVICE_TYPE_DATA, SERVICE_TYPE_SMS),
6423                 allowedServiceForPlmn);
6424     }
6425 
6426     @Test
testSupportedSatelliteServices_WithoutDataEntitlement_NoMmsServiceWithConfig()6427     public void testSupportedSatelliteServices_WithoutDataEntitlement_NoMmsServiceWithConfig()
6428             throws Exception {
6429         logd("TestGetSupportedSatelliteServicesForPlmn_WithEntitlement");
6430 
6431         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
6432                 mSatelliteControllerUT, new SparseArray<>());
6433         List<String> overlayConfigPlmnList = new ArrayList<>();
6434         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6435                 mSatelliteControllerUT, overlayConfigPlmnList);
6436         mCarrierConfigBundle.putBoolean(
6437                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6438         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6439                 true);
6440         mCarrierConfigBundle.putInt(
6441                 CarrierConfigManager.KEY_SATELLITE_DATA_SUPPORT_MODE_INT,
6442                 SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED);
6443         PersistableBundle carrierSupportedSatelliteServicesPerProvider =
6444                 new PersistableBundle();
6445         List<String> carrierConfigPlmnList = List.of("00101", "00102", "00103");
6446         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6447                 carrierConfigPlmnList.get(0), new int[]{2, 3});
6448         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6449                 carrierConfigPlmnList.get(1), new int[]{2, 3});
6450         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6451                 carrierConfigPlmnList.get(2), new int[]{2, 3});
6452         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
6453                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
6454                 carrierSupportedSatelliteServicesPerProvider);
6455         invokeCarrierConfigChanged();
6456 
6457         List<String> entitlementPlmnList =
6458                 Arrays.stream(new String[]{"00101", "00102", "00103", "00104"})
6459                         .toList();
6460         List<String> barredPlmnList = new ArrayList<>();
6461         Map<String, List<Integer>> serviceTypeListMap = Map.of(
6462                 "00101", List.of(SERVICE_TYPE_SMS),
6463                 "00102", List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS),
6464                 "00103", List.of());
6465         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6466                 entitlementPlmnList, barredPlmnList, new HashMap<>(), serviceTypeListMap,
6467                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6468 
6469         List<Integer> allowedServiceForPlmn;
6470         allowedServiceForPlmn = mSatelliteControllerUT
6471                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00101");
6472         assertEquals(List.of(SERVICE_TYPE_SMS, SERVICE_TYPE_DATA), allowedServiceForPlmn);
6473 
6474         allowedServiceForPlmn = mSatelliteControllerUT
6475                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00102");
6476         assertEquals(List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS, SERVICE_TYPE_DATA),
6477                 allowedServiceForPlmn);
6478 
6479         allowedServiceForPlmn = mSatelliteControllerUT
6480                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00103");
6481         assertEquals(List.of(SERVICE_TYPE_DATA, SERVICE_TYPE_SMS), allowedServiceForPlmn);
6482     }
6483 
6484     @Test
testSupportedSatelliteServices_WithoutDataEntitlement_NonRestrictedMode()6485     public void testSupportedSatelliteServices_WithoutDataEntitlement_NonRestrictedMode()
6486             throws Exception {
6487         logd("TestGetSupportedSatelliteServicesForPlmn_WithEntitlement");
6488 
6489         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
6490                 mSatelliteControllerUT, new SparseArray<>());
6491         List<String> overlayConfigPlmnList = new ArrayList<>();
6492         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6493                 mSatelliteControllerUT, overlayConfigPlmnList);
6494         mCarrierConfigBundle.putBoolean(
6495                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6496         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6497                 true);
6498         mCarrierConfigBundle.putInt(
6499                 CarrierConfigManager.KEY_SATELLITE_DATA_SUPPORT_MODE_INT,
6500                 SATELLITE_DATA_SUPPORT_BANDWIDTH_CONSTRAINED);
6501         PersistableBundle carrierSupportedSatelliteServicesPerProvider =
6502                 new PersistableBundle();
6503         List<String> carrierConfigPlmnList = List.of("00101", "00102", "00103");
6504         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6505                 carrierConfigPlmnList.get(0), new int[]{2, 3, 6});
6506         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6507                 carrierConfigPlmnList.get(1), new int[]{2, 3, 6});
6508         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6509                 carrierConfigPlmnList.get(2), new int[]{2, 3, 6});
6510         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
6511                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
6512                 carrierSupportedSatelliteServicesPerProvider);
6513         invokeCarrierConfigChanged();
6514 
6515         List<String> entitlementPlmnList =
6516                 Arrays.stream(new String[]{"00101", "00102", "00103", "00104"})
6517                         .toList();
6518         List<String> barredPlmnList = new ArrayList<>();
6519         Map<String, List<Integer>> serviceTypeListMap = Map.of(
6520                 "00101", List.of(SERVICE_TYPE_SMS),
6521                 "00102", List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS),
6522                 "00103", List.of());
6523         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6524                 entitlementPlmnList, barredPlmnList, new HashMap<>(), serviceTypeListMap,
6525                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6526 
6527         List<Integer> allowedServiceForPlmn;
6528         allowedServiceForPlmn = mSatelliteControllerUT
6529                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00101");
6530         assertEquals(List.of(SERVICE_TYPE_SMS), allowedServiceForPlmn);
6531 
6532         allowedServiceForPlmn = mSatelliteControllerUT
6533                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00102");
6534         assertEquals(List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS),
6535                 allowedServiceForPlmn);
6536 
6537         allowedServiceForPlmn = mSatelliteControllerUT
6538                 .getSupportedSatelliteServicesForPlmn(SUB_ID, "00103");
6539         assertEquals(List.of(SERVICE_TYPE_DATA, SERVICE_TYPE_SMS, SERVICE_TYPE_MMS),
6540                 allowedServiceForPlmn);
6541     }
6542 
6543     @Test
testGetSupportedSatelliteServicesForPlmn_WithoutEntitlement()6544     public void testGetSupportedSatelliteServicesForPlmn_WithoutEntitlement() throws Exception {
6545         logd("TestGetSupportedSatelliteServicesForPlmn_WithoutAllowedServices");
6546 
6547         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
6548                 mSatelliteControllerUT, new SparseArray<>());
6549         List<String> overlayConfigPlmnList = new ArrayList<>();
6550         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6551                 mSatelliteControllerUT, overlayConfigPlmnList);
6552         mCarrierConfigBundle.putBoolean(
6553                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6554         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6555                 true);
6556 
6557         List<String> entitlementPlmnList =
6558                 Arrays.stream(new String[]{"00101", "00102", "00103", "00104"})
6559                         .toList();
6560         List<String> barredPlmnList = new ArrayList<>();
6561         Map<String, Integer> dataPlanListMap =  new HashMap<>();
6562         Map<String, List<Integer>> allowedServiceListMap = new HashMap<>();
6563         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6564                 entitlementPlmnList, barredPlmnList, dataPlanListMap, allowedServiceListMap,
6565                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6566 
6567         // Verify whether the carrier config plmn list is returned with conditions below
6568         // the config data plmn list : empty
6569         // the carrier config plmn list : exist with services {{2}}
6570         setConfigData(new ArrayList<>());
6571         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6572                 true);
6573         PersistableBundle carrierSupportedSatelliteServicesPerProvider =
6574                 new PersistableBundle();
6575         List<String> carrierConfigPlmnList = List.of("00101");
6576         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6577                 carrierConfigPlmnList.get(0), new int[]{2, 3, 6});
6578         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
6579                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
6580                 carrierSupportedSatelliteServicesPerProvider);
6581         invokeCarrierConfigChanged();
6582 
6583         List<Integer> servicesPerPlmn;
6584         servicesPerPlmn = mSatelliteControllerUT.getSupportedSatelliteServicesForPlmn(
6585                 SUB_ID, "00101");
6586         assertEquals(Arrays.asList(SERVICE_TYPE_DATA, SERVICE_TYPE_SMS, SERVICE_TYPE_MMS).stream()
6587                         .sorted().toList(), servicesPerPlmn.stream().sorted().toList());
6588     }
6589 
6590     @Test
testGetSupportedSatelliteDataModeForPlmn_WithEntitlement()6591     public void testGetSupportedSatelliteDataModeForPlmn_WithEntitlement() throws Exception {
6592         logd("testGetSupportedSatelliteDataModeForPlmn_WithEntitlement");
6593 
6594         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
6595                 mSatelliteControllerUT, new SparseArray<>());
6596         List<String> overlayConfigPlmnList = new ArrayList<>();
6597         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6598                 mSatelliteControllerUT, overlayConfigPlmnList);
6599         mCarrierConfigBundle.putBoolean(
6600                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6601         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6602                 true);
6603 
6604         List<String> entitlementPlmnList =
6605                 Arrays.stream(new String[]{"00101", "00102", "00103", "00104"})
6606                         .toList();
6607         List<String> barredPlmnList = new ArrayList<>();
6608         Map<String, Integer> dataServicePolicyMap = Map.of(
6609                 "00101", SATELLITE_DATA_SUPPORT_BANDWIDTH_CONSTRAINED,
6610                 "00102", SATELLITE_DATA_SUPPORT_ALL
6611         );
6612         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6613                 entitlementPlmnList, barredPlmnList, new HashMap<>(), new HashMap<>(),
6614                 dataServicePolicyMap, new HashMap<>(), mIIntegerConsumer);
6615 
6616         int dataSupportModeForPlmn;
6617         dataSupportModeForPlmn = mSatelliteControllerUT
6618                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, "00101");
6619         assertEquals(SATELLITE_DATA_SUPPORT_BANDWIDTH_CONSTRAINED, dataSupportModeForPlmn);
6620 
6621         dataSupportModeForPlmn = mSatelliteControllerUT
6622                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, "00102");
6623         assertEquals(SATELLITE_DATA_SUPPORT_ALL, dataSupportModeForPlmn);
6624 
6625         dataSupportModeForPlmn = mSatelliteControllerUT
6626                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, "");
6627         assertEquals(SATELLITE_DATA_SUPPORT_ALL, dataSupportModeForPlmn);
6628 
6629         dataSupportModeForPlmn = mSatelliteControllerUT
6630                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, null);
6631         assertEquals(SATELLITE_DATA_SUPPORT_ALL, dataSupportModeForPlmn);
6632     }
6633 
6634     @Test
testGetSupportedSatelliteDataModeForPlmn_WithoutEntitlement()6635     public void testGetSupportedSatelliteDataModeForPlmn_WithoutEntitlement() throws Exception {
6636         logd("testGetSupportedSatelliteDataModeForPlmn_WithoutEntitlement");
6637 
6638         replaceInstance(SatelliteController.class, "mMergedPlmnListPerCarrier",
6639                 mSatelliteControllerUT, new SparseArray<>());
6640         List<String> overlayConfigPlmnList = new ArrayList<>();
6641         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6642                 mSatelliteControllerUT, overlayConfigPlmnList);
6643         mCarrierConfigBundle.putBoolean(
6644                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6645         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6646                 true);
6647 
6648         List<String> entitlementPlmnList =
6649                 Arrays.stream(new String[]{"00101", "00102", "00103", "00104"})
6650                         .toList();
6651         List<String> barredPlmnList = new ArrayList<>();
6652         Map<String, Integer> dataServicePolicyMap = new HashMap<>();
6653         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6654                 entitlementPlmnList, barredPlmnList, new HashMap<>(), new HashMap<>(),
6655                 dataServicePolicyMap, new HashMap<>(), mIIntegerConsumer);
6656 
6657         // when Available satellite services is not configured with data service
6658         mCarrierConfigBundle.putInt(
6659                 CarrierConfigManager.KEY_SATELLITE_DATA_SUPPORT_MODE_INT,
6660                 SATELLITE_DATA_SUPPORT_BANDWIDTH_CONSTRAINED);
6661         int dataSupportModeForPlmn = mSatelliteControllerUT
6662                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, "00101");
6663         assertEquals(SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED, dataSupportModeForPlmn);
6664 
6665         dataSupportModeForPlmn = mSatelliteControllerUT
6666                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, "");
6667         assertEquals(SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED, dataSupportModeForPlmn);
6668 
6669         dataSupportModeForPlmn = mSatelliteControllerUT
6670                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, null);
6671         assertEquals(SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED, dataSupportModeForPlmn);
6672 
6673         setConfigData(new ArrayList<>());
6674         PersistableBundle carrierSupportedSatelliteServicesPerProvider =
6675                 new PersistableBundle();
6676         List<String> carrierConfigPlmnList = List.of("00101");
6677         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6678                 carrierConfigPlmnList.get(0), new int[]{2, 3, 5});
6679         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
6680                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
6681                 carrierSupportedSatelliteServicesPerProvider);
6682         invokeCarrierConfigChanged();
6683 
6684         // when Available satellite services support data service
6685         dataSupportModeForPlmn = mSatelliteControllerUT
6686                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, "00101");
6687         assertEquals(SATELLITE_DATA_SUPPORT_BANDWIDTH_CONSTRAINED, dataSupportModeForPlmn);
6688 
6689         dataSupportModeForPlmn = mSatelliteControllerUT
6690                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, "");
6691         assertEquals(SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED, dataSupportModeForPlmn);
6692 
6693         dataSupportModeForPlmn = mSatelliteControllerUT
6694                 .getSatelliteDataServicePolicyForPlmn(SUB_ID, null);
6695         assertEquals(SATELLITE_DATA_SUPPORT_ONLY_RESTRICTED, dataSupportModeForPlmn);
6696     }
6697 
6698     @Test
testNotifyCarrierRoamingNtnAvailableServicesChanged_noServices()6699     public void testNotifyCarrierRoamingNtnAvailableServicesChanged_noServices() throws Exception {
6700         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
6701         mSatelliteControllerUT.setCallOnlySuperMethod();
6702         List<String> overlayConfigPlmnList = new ArrayList<>();
6703         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6704                 mSatelliteControllerUT, overlayConfigPlmnList);
6705         mCarrierConfigBundle.putBoolean(
6706                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6707         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6708                 true);
6709         mCarrierConfigBundle.putIntArray(
6710                 CarrierConfigManager.KEY_CARRIER_ROAMING_SATELLITE_DEFAULT_SERVICES_INT_ARRAY,
6711                 new int[]{});
6712         invokeCarrierConfigChanged();
6713         List<String> entitlementPlmnList = Arrays.stream(
6714                 new String[]{"00101", "00102", "00103", "00104"}).toList();
6715         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6716                 entitlementPlmnList, new ArrayList<>(), new HashMap<>(),
6717                 new HashMap<>() /*serviceTypeListMap*/, new HashMap<>(), new HashMap<>(),
6718                 mIIntegerConsumer);
6719         verify(mPhone, times(2)).notifyCarrierRoamingNtnAvailableServicesChanged(
6720                 (int[]) ArgumentMatchers.any());
6721     }
6722 
6723     @Test
testNotifyCarrierRoamingNtnAvailableServicesChanged()6724     public void testNotifyCarrierRoamingNtnAvailableServicesChanged() throws Exception {
6725         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
6726         mSatelliteControllerUT.setCallOnlySuperMethod();
6727         List<String> overlayConfigPlmnList = new ArrayList<>();
6728         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6729                 mSatelliteControllerUT, overlayConfigPlmnList);
6730         mCarrierConfigBundle.putBoolean(
6731                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6732         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6733                 true);
6734         invokeCarrierConfigChanged();
6735 
6736         List<String> entitlementPlmnList = Arrays.stream(
6737                 new String[]{"00101", "00102", "00103", "00104"}).toList();
6738         List<String> barredPlmnList = new ArrayList<>();
6739         Map<String, List<Integer>> serviceTypeListMap = Map.of("00101",
6740                 List.of(SERVICE_TYPE_DATA, SERVICE_TYPE_SMS), "00102",
6741                 List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS), "00103",
6742                 List.of(SERVICE_TYPE_DATA, SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS));
6743         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6744                 entitlementPlmnList, barredPlmnList, new HashMap<>(), serviceTypeListMap,
6745                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6746         int[] expectedServices = new int[]{1, 2, 3};
6747         int[] supportedServices = mSatelliteControllerUT.getSupportedServicesOnCarrierRoamingNtn(
6748                 SUB_ID);
6749         assertArrayEquals(expectedServices, supportedServices);
6750         verify(mPhone, times(2)).notifyCarrierRoamingNtnAvailableServicesChanged(
6751                 (int[]) ArgumentMatchers.any());
6752     }
6753 
6754     @Test
testNotifyCarrierRoamingNtnAvailableServicesChange_duplicateUpdates()6755     public void testNotifyCarrierRoamingNtnAvailableServicesChange_duplicateUpdates()
6756             throws Exception {
6757         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
6758         mSatelliteControllerUT.setCallOnlySuperMethod();
6759         List<String> overlayConfigPlmnList = new ArrayList<>();
6760         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6761                 mSatelliteControllerUT, overlayConfigPlmnList);
6762         mCarrierConfigBundle.putBoolean(
6763                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6764         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6765                 true);
6766         invokeCarrierConfigChanged();
6767 
6768         List<String> entitlementPlmnList = Arrays.stream(
6769                 new String[]{"00101", "00102", "00103", "00104"}).toList();
6770         List<String> barredPlmnList = new ArrayList<>();
6771         Map<String, List<Integer>> serviceTypeListMap = Map.of("00101",
6772                 List.of(SERVICE_TYPE_DATA, SERVICE_TYPE_SMS), "00102",
6773                 List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS), "00103",
6774                 List.of(SERVICE_TYPE_DATA, SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS));
6775         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6776                 entitlementPlmnList, barredPlmnList, new HashMap<>(), serviceTypeListMap,
6777                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6778         int[] expectedServices = new int[]{1, 2, 3};
6779         int[] supportedServices = mSatelliteControllerUT.getSupportedServicesOnCarrierRoamingNtn(
6780                 SUB_ID);
6781         assertArrayEquals(expectedServices, supportedServices);
6782         verify(mPhone, times(2)).notifyCarrierRoamingNtnAvailableServicesChanged(
6783                 (int[]) ArgumentMatchers.any());
6784 
6785         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6786                 entitlementPlmnList, barredPlmnList, new HashMap<>(), serviceTypeListMap,
6787                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6788         // There is no change in services between 2 calls, so notify should not invoke again.
6789         supportedServices = mSatelliteControllerUT.getSupportedServicesOnCarrierRoamingNtn(SUB_ID);
6790         assertArrayEquals(expectedServices, supportedServices);
6791         verify(mPhone, times(2)).notifyCarrierRoamingNtnAvailableServicesChanged(
6792                 (int[]) ArgumentMatchers.any());
6793     }
6794 
6795     @Test
testNotifyCarrierRoamingNtnAvailableServicesChange_multipleUpdates()6796     public void testNotifyCarrierRoamingNtnAvailableServicesChange_multipleUpdates()
6797             throws Exception {
6798         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
6799         mSatelliteControllerUT.setCallOnlySuperMethod();
6800         List<String> overlayConfigPlmnList = new ArrayList<>();
6801         replaceInstance(SatelliteController.class, "mSatellitePlmnListFromOverlayConfig",
6802                 mSatelliteControllerUT, overlayConfigPlmnList);
6803         mCarrierConfigBundle.putBoolean(
6804                 CarrierConfigManager.KEY_SATELLITE_ENTITLEMENT_SUPPORTED_BOOL, true);
6805         mCarrierConfigBundle.putBoolean(CarrierConfigManager.KEY_SATELLITE_ATTACH_SUPPORTED_BOOL,
6806                 true);
6807         invokeCarrierConfigChanged();
6808 
6809         List<String> entitlementPlmnList = Arrays.stream(
6810                 new String[]{"00101", "00102", "00103", "00104"}).toList();
6811         List<String> barredPlmnList = new ArrayList<>();
6812         Map<String, List<Integer>> serviceTypeListMap = Map.of("00101",
6813                 List.of(SERVICE_TYPE_DATA, SERVICE_TYPE_SMS), "00102",
6814                 List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS), "00103",
6815                 List.of(SERVICE_TYPE_DATA, SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS));
6816         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6817                 entitlementPlmnList, barredPlmnList, new HashMap<>(), serviceTypeListMap,
6818                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6819         int[] expectedServices = new int[]{1, 2, 3};
6820         int[] supportedServices = mSatelliteControllerUT.getSupportedServicesOnCarrierRoamingNtn(
6821                 SUB_ID);
6822         assertArrayEquals(expectedServices, supportedServices);
6823         verify(mPhone, times(2)).notifyCarrierRoamingNtnAvailableServicesChanged(
6824                 (int[]) ArgumentMatchers.any());
6825 
6826         serviceTypeListMap = Map.of("00101", List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS), "00102",
6827                 List.of(SERVICE_TYPE_SMS), "00103", List.of(SERVICE_TYPE_VOICE, SERVICE_TYPE_SMS));
6828         mSatelliteControllerUT.onSatelliteEntitlementStatusUpdated(SUB_ID, false,
6829                 entitlementPlmnList, barredPlmnList, new HashMap<>(), serviceTypeListMap,
6830                 new HashMap<>(), new HashMap<>(), mIIntegerConsumer);
6831         expectedServices = new int[]{1, 3};
6832         supportedServices = mSatelliteControllerUT.getSupportedServicesOnCarrierRoamingNtn(SUB_ID);
6833         assertArrayEquals(expectedServices, supportedServices);
6834         // 2 times notify called due to previous and current changes
6835         verify(mPhone, times(3)).notifyCarrierRoamingNtnAvailableServicesChanged(
6836                 (int[]) ArgumentMatchers.any());
6837     }
6838 
6839     @Test
testGetPhoneNumberBasedCarrier()6840     public void testGetPhoneNumberBasedCarrier() throws Exception {
6841         assertEquals("", mSatelliteControllerUT.getPhoneNumberBasedCarrier(-1));
6842 
6843         int carrierId_subID = 0;
6844         SubscriptionInfoInternal subInfoInternal =
6845                 new SubscriptionInfoInternal.Builder().setCarrierId(
6846                         carrierId_subID).setImsi("").setIccId(mIccId).build();
6847         doReturn(subInfoInternal).when(mMockSubscriptionManagerService)
6848                 .getSubscriptionInfoInternal(eq(SUB_ID));
6849 
6850         // subscriptionManager is null
6851         Field field = SatelliteController.class.getDeclaredField("mInjectSubscriptionManager");
6852         field.setAccessible(true);
6853         field.set(mSatelliteControllerUT, null);
6854         assertEquals("", mSatelliteControllerUT.getPhoneNumberBasedCarrier(SUB_ID));
6855 
6856         // phoneNumber is empty
6857         field.set(mSatelliteControllerUT, mSubscriptionManager);
6858         doReturn("").when(mSubscriptionManager).getPhoneNumber(eq(SUB_ID));
6859         assertEquals("", mSatelliteControllerUT.getPhoneNumberBasedCarrier(SUB_ID));
6860 
6861         // IMSI is empty
6862         doReturn(mMsisdn).when(mSubscriptionManager).getPhoneNumber(eq(SUB_ID));
6863         assertEquals("", mSatelliteControllerUT.getPhoneNumberBasedCarrier(SUB_ID));
6864 
6865         // IMSI length is less than 6
6866         subInfoInternal = new SubscriptionInfoInternal.Builder().setCarrierId(
6867                         carrierId_subID).setImsi("12345").setIccId(mIccId).build();
6868         doReturn(subInfoInternal).when(mMockSubscriptionManagerService)
6869                 .getSubscriptionInfoInternal(eq(SUB_ID));
6870         assertEquals("", mSatelliteControllerUT.getPhoneNumberBasedCarrier(SUB_ID));
6871 
6872         subInfoInternal = new SubscriptionInfoInternal.Builder().setCarrierId(
6873                 carrierId_subID).setImsi(mImsi).setIccId(mIccId).build();
6874         doReturn(subInfoInternal).when(mMockSubscriptionManagerService)
6875                 .getSubscriptionInfoInternal(eq(SUB_ID));
6876         String expectedResult = "123456" + "0987654321";
6877         assertEquals(expectedResult, mSatelliteControllerUT.getPhoneNumberBasedCarrier(SUB_ID));
6878     }
6879 
6880     @Test
testEvaluateCarrierRoamingNtnEligibilityChange_inSatelliteMode()6881     public void testEvaluateCarrierRoamingNtnEligibilityChange_inSatelliteMode() {
6882         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
6883 
6884         mSatelliteControllerUT.isSatelliteEnabledOrBeingEnabled = true;
6885         mSatelliteControllerUT.setSatellitePhone(1);
6886         mSatelliteControllerUT.setSelectedSatelliteSubId(SUB_ID);
6887         mSatelliteControllerUT.isSatelliteProvisioned = true;
6888         mSatelliteControllerUT.isSatelliteAllowedCallback = null;
6889         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
6890         mSatelliteControllerUT.setIsSatelliteAllowedState(true);
6891         sendCmdEvaluateCarrierRoamingNtnEligibilityChange();
6892         processAllMessages();
6893         verify(mPhone, times(0)).notifyCarrierRoamingNtnEligibleStateChanged(anyBoolean());
6894     }
6895 
6896     @Test
testExitOutOfP2pSessionIfSatelliteIsNotAllowed()6897     public void testExitOutOfP2pSessionIfSatelliteIsNotAllowed() throws Exception {
6898         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
6899         when(mFeatureFlags.satelliteExitP2pSessionOutsideGeofence()).thenReturn(true);
6900 
6901         // Enable satellite P2P session
6902         setUpResponseForRequestIsSatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
6903         verifySatelliteSupported(true, SATELLITE_RESULT_SUCCESS);
6904         setUpResponseForRequestIsSatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
6905         verifySatelliteProvisioned(true, SATELLITE_RESULT_SUCCESS);
6906         setUpResponseForRequestSatelliteEnabled(true, false, false, SATELLITE_RESULT_SUCCESS);
6907         mSatelliteControllerUT.requestSatelliteEnabled(true, false, false, mIIntegerConsumer);
6908         processAllMessages();
6909         assertTrue(waitForIIntegerConsumerResult(1));
6910         assertEquals(SATELLITE_RESULT_SUCCESS, (long) mIIntegerConsumerResults.get(0));
6911         verifySatelliteEnabled(true, SATELLITE_RESULT_SUCCESS);
6912 
6913         ArgumentCaptor<SatelliteModemEnableRequestAttributes> enableSatelliteRequest =
6914                 ArgumentCaptor.forClass(SatelliteModemEnableRequestAttributes.class);
6915         ArgumentCaptor<Message> enableSatelliteResponse = ArgumentCaptor.forClass(Message.class);
6916 
6917         reset(mMockSatelliteModemInterface);
6918         doReturn(true).when(mMockSatelliteModemInterface).isSatelliteServiceSupported();
6919         // Set access allowed to false
6920         final int carrierSubId = SUB_ID;
6921         final int oemSubId = SUB_ID1;
6922         setSatelliteSubscriberTesting(false);
6923         mSatelliteControllerUT.subsInfoListPerPriority().computeIfAbsent(
6924                         getKeyPriority(testSubscriptionInfo), k -> new ArrayList<>())
6925                 .add(testSubscriptionInfo);
6926         mSatelliteControllerUT.subsInfoListPerPriority().computeIfAbsent(
6927                         getKeyPriority(testSubscriptionInfo2), k -> new ArrayList<>())
6928                 .add(testSubscriptionInfo2);
6929         mSatelliteControllerUT.selectedSatelliteSubId = SUB_ID1;
6930         mSatelliteControllerUT.handleSatelliteAccessAllowedStateChanged(false);
6931         processAllMessages();
6932         verify(mMockSatelliteModemInterface).requestSatelliteEnabled(
6933                 enableSatelliteRequest.capture(), enableSatelliteResponse.capture());
6934 
6935         // Disable satellite request is sent to modem
6936         SatelliteModemEnableRequestAttributes request = enableSatelliteRequest.getValue();
6937         assertFalse(request.isEnabled());
6938         assertFalse(request.isForDemoMode());
6939         assertFalse(request.isForEmergencyMode());
6940         // OEM satellite subscription should be selected as current location is not supported
6941         assertEquals(oemSubId, mSatelliteControllerUT.getSelectedSatelliteSubId());
6942 
6943         // As current location is allowed, carrier subscription should be selected
6944         mSatelliteControllerUT.selectedSatelliteSubId = SUB_ID;
6945         mSatelliteControllerUT.handleSatelliteAccessAllowedStateChanged(true);
6946         processAllMessages();
6947         assertEquals(carrierSubId, mSatelliteControllerUT.getSelectedSatelliteSubId());
6948 
6949         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
6950         when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
6951         when(mServiceState2.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
6952         when(mServiceState.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(null);
6953         when(mServiceState2.getNetworkRegistrationInfo(anyInt(), anyInt())).thenReturn(null);
6954         mSatelliteControllerUT.mIsApplicationSupportsP2P = true;
6955         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
6956         mCarrierConfigBundle.putInt(KEY_CARRIER_ROAMING_NTN_CONNECT_TYPE_INT, 1);
6957         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ROAMING_P2P_SMS_SUPPORTED_BOOL, true);
6958         int[] supportedServices2 = {2};
6959         int[] supportedServices3 = {1, 3};
6960         PersistableBundle carrierSupportedSatelliteServicesPerProvider = new PersistableBundle();
6961         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6962                 "00102", supportedServices2);
6963         carrierSupportedSatelliteServicesPerProvider.putIntArray(
6964                 "00103", supportedServices3);
6965         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
6966                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
6967                 carrierSupportedSatelliteServicesPerProvider);
6968         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
6969                 : mCarrierConfigChangedListenerList) {
6970             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
6971                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
6972             );
6973         }
6974         mSatelliteControllerUT.setSatellitePhone(1);
6975         mSatelliteControllerUT.setSelectedSatelliteSubId(SUB_ID);
6976         mSatelliteControllerUT.isSatelliteProvisioned = true;
6977         processAllMessages();
6978 
6979         assertTrue(mSatelliteControllerUT.isCarrierRoamingNtnEligible(mPhone));
6980     }
6981 
6982     @Test
testIsSatelliteAvailableAtCurrentLocation()6983     public void testIsSatelliteAvailableAtCurrentLocation() throws Exception {
6984         SubscriptionInfo ntnOnlySubscriptionInfo = new SubscriptionInfo.Builder()
6985                 .setOnlyNonTerrestrialNetwork(true)
6986                 .build();
6987         SubscriptionInfo esosSubscriptionInfo = new SubscriptionInfo.Builder()
6988                 .setSatelliteESOSSupported(true)
6989                 .build();
6990         Field currentLocationTagIdsField = SatelliteController.class.getDeclaredField(
6991                 "mCurrentLocationTagIds");
6992         currentLocationTagIdsField.setAccessible(true);
6993 
6994         // Null subscription info
6995         assertFalse(mSatelliteControllerUT.isSatelliteAvailableAtCurrentLocation(null));
6996 
6997         // Satellite is not allowed
6998         mSatelliteControllerUT.setIsSatelliteAllowedState(false);
6999         assertFalse(mSatelliteControllerUT.isSatelliteAvailableAtCurrentLocation(
7000                 ntnOnlySubscriptionInfo));
7001         assertFalse(mSatelliteControllerUT.isSatelliteAvailableAtCurrentLocation(
7002                 esosSubscriptionInfo));
7003 
7004         // Satellite is allowed
7005         mSatelliteControllerUT.setIsSatelliteAllowedState(true);
7006         assertTrue(mSatelliteControllerUT.isSatelliteAvailableAtCurrentLocation(
7007                 ntnOnlySubscriptionInfo));
7008 
7009         // Both config_verizon_satellite_enabled_tagids and satellite_access_config_file
7010         // are not configured
7011         assertTrue(mSatelliteControllerUT.isSatelliteAvailableAtCurrentLocation(
7012                 esosSubscriptionInfo));
7013 
7014         // config_verizon_satellite_enabled_tagids is not configured whereas
7015         // satellite_access_config_file is configured
7016         mContextFixture.putResource(
7017                 com.android.internal.R.string.satellite_access_config_file,
7018                 "test_satellite_access_config_file");
7019         assertFalse(mSatelliteControllerUT.isSatelliteAvailableAtCurrentLocation(
7020                 esosSubscriptionInfo));
7021 
7022         // Both config_verizon_satellite_enabled_tagids and satellite_access_config_file
7023         // are configured, but mCurrentLocationTagIds is empty
7024         mContextFixture.putIntArrayResource(
7025                 R.array.config_verizon_satellite_enabled_tagids,
7026                 new int[]{1001});
7027         assertFalse(mSatelliteControllerUT.isSatelliteAvailableAtCurrentLocation(
7028                 esosSubscriptionInfo));
7029 
7030         // Both config_verizon_satellite_enabled_tagids and satellite_access_config_file
7031         // are configured, and mCurrentLocationTagIds contains the carrier tag id
7032         currentLocationTagIdsField.set(mSatelliteControllerUT, Arrays.asList(1001));
7033         assertTrue(mSatelliteControllerUT.isSatelliteAvailableAtCurrentLocation(
7034                 esosSubscriptionInfo));
7035     }
7036 
testNotifyNtnEligibilityLocationServiceStatusChanged()7037     public void testNotifyNtnEligibilityLocationServiceStatusChanged() {
7038         // Enable CarrierRoamingNtn
7039         mContextFixture.putBooleanResource(
7040                 R.bool.config_satellite_should_notify_availability, true);
7041         when(mFeatureFlags.carrierRoamingNbIotNtn()).thenReturn(true);
7042         when(mServiceState2.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
7043         when(mServiceState.getState()).thenReturn(ServiceState.STATE_OUT_OF_SERVICE);
7044         mSatelliteControllerUT.mIsApplicationSupportsP2P = true;
7045         mSatelliteControllerUT.setIsSatelliteSupported(true);
7046         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ATTACH_SUPPORTED_BOOL, true);
7047         mCarrierConfigBundle.putInt(KEY_CARRIER_ROAMING_NTN_CONNECT_TYPE_INT,
7048                 CARRIER_ROAMING_NTN_CONNECT_MANUAL);
7049         mCarrierConfigBundle.putInt(
7050                 KEY_CARRIER_SUPPORTED_SATELLITE_NOTIFICATION_HYSTERESIS_SEC_INT, 1 * 60);
7051         mCarrierConfigBundle.putBoolean(KEY_SATELLITE_ROAMING_P2P_SMS_SUPPORTED_BOOL, true);
7052         int[] supportedServices2 = {2};
7053         int[] supportedServices3 = {1, 3};
7054         PersistableBundle carrierSupportedSatelliteServicesPerProvider = new PersistableBundle();
7055         carrierSupportedSatelliteServicesPerProvider.putIntArray(
7056                 "00102", supportedServices2);
7057         carrierSupportedSatelliteServicesPerProvider.putIntArray(
7058                 "00103", supportedServices3);
7059         mCarrierConfigBundle.putPersistableBundle(CarrierConfigManager
7060                         .KEY_CARRIER_SUPPORTED_SATELLITE_SERVICES_PER_PROVIDER_BUNDLE,
7061                 carrierSupportedSatelliteServicesPerProvider);
7062         for (Pair<Executor, CarrierConfigManager.CarrierConfigChangeListener> pair
7063                 : mCarrierConfigChangedListenerList) {
7064             pair.first.execute(() -> pair.second.onCarrierConfigChanged(
7065                     /*slotIndex*/ 0, /*subId*/ SUB_ID, /*carrierId*/ 0, /*specificCarrierId*/ 0)
7066             );
7067         }
7068         mSatelliteControllerUT.setSatellitePhone(1);
7069         mSatelliteControllerUT.setSelectedSatelliteSubId(SUB_ID);
7070         mSatelliteControllerUT.isSatelliteProvisioned = true;
7071         mSatelliteControllerUT.isSatelliteAllowedCallback = null;
7072         mSatelliteControllerUT.setIsSatelliteAllowedState(true);
7073         processAllMessages();
7074         clearInvocations(mPhone);
7075 
7076         doReturn(LocationManager.MODE_CHANGED_ACTION).when(mMockLocationIntent).getAction();
7077 
7078         // Location service off
7079         mSatelliteControllerUT.setLocationServiceEnabled(false);
7080         BroadcastReceiver receiver = mSatelliteControllerUT.getLocationReceiver();
7081         receiver.onReceive(mContext, mMockLocationIntent);
7082 
7083         processAllMessages();
7084 
7085         verify(mPhone, times(1)).notifyCarrierRoamingNtnEligibleStateChanged(eq(false));
7086         clearInvocations(mPhone);
7087 
7088         // Location service off
7089         mSatelliteControllerUT.setLocationServiceEnabled(true);
7090         receiver.onReceive(mContext, mMockLocationIntent);
7091 
7092         processAllMessages();
7093 
7094         verify(mPhone, times(1)).notifyCarrierRoamingNtnEligibleStateChanged(eq(true));
7095     }
7096 
7097     @Test
testGetSatelliteEnabledForCarrier()7098     public void testGetSatelliteEnabledForCarrier() {
7099         reset(mPhone);
7100         sendCmdGetSatelliteEnabledForCarrier(mPhone);
7101         processAllMessages();
7102         verify(mPhone, times(1)).isSatelliteEnabledForCarrier(anyInt(), any());
7103         reset(mPhone);
7104 
7105         sendEventGetSatelliteEnabledForCarrierDone(mPhone.getSubId(), false,
7106                 new SatelliteException(SATELLITE_RESULT_ERROR));
7107         processAllMessages();
7108         assertFalse(mSatelliteControllerUT.isSatelliteEnabledForCarrierAtModem(mPhone.getSubId()));
7109 
7110         sendEventGetSatelliteEnabledForCarrierDone(mPhone.getSubId(), true, null);
7111         processAllMessages();
7112         assertTrue(mSatelliteControllerUT.isSatelliteEnabledForCarrierAtModem(mPhone.getSubId()));
7113 
7114         sendEventGetSatelliteEnabledForCarrierDone(mPhone.getSubId(), false, null);
7115         processAllMessages();
7116         assertFalse(mSatelliteControllerUT.isSatelliteEnabledForCarrierAtModem(mPhone.getSubId()));
7117     }
7118 
7119 }
7120