blob: f70ca86eafcd59d4a84f3fe32bf0dec99aceabdc [file] [log] [blame]
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -08001/*
2 * Copyright (C) 2016 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
Ashutosh Joshi420e45e2016-12-20 16:34:41 -080017package com.android.server.location;
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -080018
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -080019import android.content.Context;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070020import android.hardware.contexthub.V1_0.AsyncEventType;
21import android.hardware.contexthub.V1_0.ContextHub;
22import android.hardware.contexthub.V1_0.ContextHubMsg;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070023import android.hardware.contexthub.V1_0.HubAppInfo;
24import android.hardware.contexthub.V1_0.IContexthub;
25import android.hardware.contexthub.V1_0.IContexthubCallback;
26import android.hardware.contexthub.V1_0.Result;
27import android.hardware.contexthub.V1_0.TransactionResult;
Ashutosh Joshi420e45e2016-12-20 16:34:41 -080028import android.hardware.location.ContextHubInfo;
Ashutosh Joshi420e45e2016-12-20 16:34:41 -080029import android.hardware.location.ContextHubMessage;
Arthur Ishiguroebb0e862017-11-17 14:55:32 -080030import android.hardware.location.ContextHubTransaction;
Ashutosh Joshi420e45e2016-12-20 16:34:41 -080031import android.hardware.location.IContextHubCallback;
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -080032import android.hardware.location.IContextHubClient;
33import android.hardware.location.IContextHubClientCallback;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070034import android.hardware.location.IContextHubService;
35import android.hardware.location.IContextHubTransactionCallback;
Ashutosh Joshi420e45e2016-12-20 16:34:41 -080036import android.hardware.location.NanoApp;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070037import android.hardware.location.NanoAppBinary;
38import android.hardware.location.NanoAppFilter;
Ashutosh Joshi420e45e2016-12-20 16:34:41 -080039import android.hardware.location.NanoAppInstanceInfo;
Arthur Ishiguroebb0e862017-11-17 14:55:32 -080040import android.hardware.location.NanoAppMessage;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070041import android.hardware.location.NanoAppState;
destradaa78cebca2016-04-14 18:40:14 -070042import android.os.RemoteCallbackList;
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -080043import android.os.RemoteException;
44import android.util.Log;
45
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060046import com.android.internal.util.DumpUtils;
47
Ashutosh Joshi6239cc62016-04-04 16:19:29 -070048import java.io.FileDescriptor;
49import java.io.PrintWriter;
Ashutosh Joshi19753cc2016-11-23 13:56:39 -080050import java.nio.ByteBuffer;
51import java.nio.ByteOrder;
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -080052import java.util.ArrayList;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070053import java.util.Collections;
Arthur Ishiguroebb0e862017-11-17 14:55:32 -080054import java.util.HashMap;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070055import java.util.List;
Arthur Ishiguroebb0e862017-11-17 14:55:32 -080056import java.util.Map;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070057import java.util.NoSuchElementException;
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -080058
59/**
60 * @hide
61 */
Peng Xu9ff7d222016-02-11 13:02:05 -080062public class ContextHubService extends IContextHubService.Stub {
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -080063 private static final String TAG = "ContextHubService";
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -080064
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070065 /*
66 * Constants for the type of transaction that is defined by ContextHubService.
67 * This is used to report the transaction callback to clients, and is different from
68 * ContextHubTransaction.Type.
69 */
70 public static final int MSG_ENABLE_NANO_APP = 1;
71 public static final int MSG_DISABLE_NANO_APP = 2;
72 public static final int MSG_LOAD_NANO_APP = 3;
Ashutosh Joshicafdee92016-04-04 16:19:29 -070073 public static final int MSG_UNLOAD_NANO_APP = 4;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070074 public static final int MSG_QUERY_NANO_APPS = 5;
75 public static final int MSG_QUERY_MEMORY = 6;
76 public static final int MSG_HUB_RESET = 7;
Ashutosh Joshib741e3b2016-03-29 09:19:56 -070077
Ashutosh Joshib741e3b2016-03-29 09:19:56 -070078 private static final int OS_APP_INSTANCE = -1;
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -080079
Peng Xu9ff7d222016-02-11 13:02:05 -080080 private final Context mContext;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070081
destradaa78cebca2016-04-14 18:40:14 -070082 private final ContextHubInfo[] mContextHubInfo;
83 private final RemoteCallbackList<IContextHubCallback> mCallbacksList =
84 new RemoteCallbackList<>();
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -080085
Arthur Ishiguro7a23a962017-11-01 10:52:28 -070086 // Proxy object to communicate with the Context Hub HAL
87 private final IContexthub mContextHubProxy;
88
89 // The manager for transaction queue
90 private final ContextHubTransactionManager mTransactionManager;
91
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -080092 // The manager for sending messages to/from clients
93 private final ContextHubClientManager mClientManager;
94
Arthur Ishiguroebb0e862017-11-17 14:55:32 -080095 // The default client for old API clients
96 private final Map<Integer, IContextHubClient> mDefaultClientMap;
97
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -080098 // The manager for the internal nanoapp state cache
99 private final NanoAppStateManager mNanoAppStateManager = new NanoAppStateManager();
100
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700101 /**
102 * Class extending the callback to register with a Context Hub.
103 */
104 private class ContextHubServiceCallback extends IContexthubCallback.Stub {
105 private final int mContextHubId;
106
107 ContextHubServiceCallback(int contextHubId) {
108 mContextHubId = contextHubId;
109 }
110
111 @Override
112 public void handleClientMsg(ContextHubMsg message) {
113 handleClientMessageCallback(mContextHubId, message);
114 }
115
116 @Override
117 public void handleTxnResult(int transactionId, int result) {
118 handleTransactionResultCallback(mContextHubId, transactionId, result);
119 }
120
121 @Override
122 public void handleHubEvent(int eventType) {
123 handleHubEventCallback(mContextHubId, eventType);
124 }
125
126 @Override
127 public void handleAppAbort(long nanoAppId, int abortCode) {
128 handleAppAbortCallback(mContextHubId, nanoAppId, abortCode);
129 }
130
131 @Override
132 public void handleAppsInfo(ArrayList<HubAppInfo> nanoAppInfoList) {
133 handleQueryAppsCallback(mContextHubId, nanoAppInfoList);
134 }
135 }
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700136
Peng Xu9ff7d222016-02-11 13:02:05 -0800137 public ContextHubService(Context context) {
138 mContext = context;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700139
140 mContextHubProxy = getContextHubProxy();
141 if (mContextHubProxy == null) {
142 mTransactionManager = null;
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800143 mClientManager = null;
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800144 mDefaultClientMap = Collections.EMPTY_MAP;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700145 mContextHubInfo = new ContextHubInfo[0];
146 return;
147 }
148
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800149 mClientManager = new ContextHubClientManager(mContext, mContextHubProxy);
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800150 mTransactionManager = new ContextHubTransactionManager(
151 mContextHubProxy, mClientManager, mNanoAppStateManager);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700152
153 List<ContextHub> hubList;
154 try {
155 hubList = mContextHubProxy.getHubs();
156 } catch (RemoteException e) {
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800157 Log.e(TAG, "RemoteException while getting Context Hub info", e);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700158 hubList = Collections.emptyList();
159 }
160 mContextHubInfo = ContextHubServiceUtil.createContextHubInfoArray(hubList);
161
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800162 HashMap<Integer, IContextHubClient> defaultClientMap = new HashMap<>();
163 for (ContextHubInfo contextHubInfo : mContextHubInfo) {
164 int contextHubId = contextHubInfo.getId();
165
166 IContextHubClient client = mClientManager.registerClient(
167 createDefaultClientCallback(contextHubId), contextHubId);
168 defaultClientMap.put(contextHubId, client);
169 }
170 mDefaultClientMap = Collections.unmodifiableMap(defaultClientMap);
171
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700172 for (ContextHubInfo contextHubInfo : mContextHubInfo) {
173 int contextHubId = contextHubInfo.getId();
174 try {
175 mContextHubProxy.registerCallback(
176 contextHubId, new ContextHubServiceCallback(contextHubId));
177 } catch (RemoteException e) {
178 Log.e(TAG, "RemoteException while registering service callback for hub (ID = "
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800179 + contextHubId + ")", e);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700180 }
181 }
182
183 // Do a query to initialize the service cache list of nanoapps
184 // TODO(b/69270990): Remove this when old API is deprecated
185 for (ContextHubInfo contextHubInfo : mContextHubInfo) {
186 queryNanoAppsInternal(contextHubInfo.getId());
187 }
Peng Xu9ff7d222016-02-11 13:02:05 -0800188
189 for (int i = 0; i < mContextHubInfo.length; i++) {
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700190 Log.d(TAG, "ContextHub[" + i + "] id: " + mContextHubInfo[i].getId()
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700191 + ", name: " + mContextHubInfo[i].getName());
Peng Xu9ff7d222016-02-11 13:02:05 -0800192 }
193 }
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -0800194
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700195 /**
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800196 * Creates a default client callback for old API clients.
197 *
198 * @param contextHubId the ID of the hub to attach this client to
199 * @return the internal callback interface
200 */
201 private IContextHubClientCallback createDefaultClientCallback(int contextHubId) {
202 return new IContextHubClientCallback.Stub() {
203 @Override
204 public void onMessageFromNanoApp(NanoAppMessage message) {
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800205 int nanoAppHandle = mNanoAppStateManager.getNanoAppHandle(
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800206 contextHubId, message.getNanoAppId());
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800207
208 onMessageReceiptOldApi(
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800209 message.getMessageType(), contextHubId, nanoAppHandle,
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800210 message.getMessageBody());
211 }
212
213 @Override
214 public void onHubReset() {
Arthur Ishiguro6d47c542017-11-17 15:49:07 -0800215 byte[] data = {TransactionResult.SUCCESS};
216 onMessageReceiptOldApi(MSG_HUB_RESET, contextHubId, OS_APP_INSTANCE, data);
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800217 }
218
219 @Override
220 public void onNanoAppAborted(long nanoAppId, int abortCode) {
221 }
222
223 @Override
224 public void onNanoAppLoaded(long nanoAppId) {
225 }
226
227 @Override
228 public void onNanoAppUnloaded(long nanoAppId) {
229 }
230
231 @Override
232 public void onNanoAppEnabled(long nanoAppId) {
233 }
234
235 @Override
236 public void onNanoAppDisabled(long nanoAppId) {
237 }
238 };
239 }
240
241 /**
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700242 * @return the IContexthub proxy interface
243 */
244 private IContexthub getContextHubProxy() {
245 IContexthub proxy = null;
246 try {
247 proxy = IContexthub.getService(true /* retry */);
248 } catch (RemoteException e) {
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800249 Log.e(TAG, "RemoteException while attaching to Context Hub HAL proxy", e);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700250 } catch (NoSuchElementException e) {
251 Log.i(TAG, "Context Hub HAL service not found");
252 }
253
254 return proxy;
255 }
256
Peng Xu9ff7d222016-02-11 13:02:05 -0800257 @Override
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700258 public int registerCallback(IContextHubCallback callback) throws RemoteException {
destradaa8bad3fe2016-03-15 12:33:40 -0700259 checkPermissions();
destradaa78cebca2016-04-14 18:40:14 -0700260 mCallbacksList.register(callback);
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800261
Ashutosh Joshi1d941812017-03-09 15:21:24 -0800262 Log.d(TAG, "Added callback, total callbacks " +
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700263 mCallbacksList.getRegisteredCallbackCount());
Peng Xu9ff7d222016-02-11 13:02:05 -0800264 return 0;
265 }
266
267 @Override
268 public int[] getContextHubHandles() throws RemoteException {
destradaa8bad3fe2016-03-15 12:33:40 -0700269 checkPermissions();
Ashutosh Joshi6239cc62016-04-04 16:19:29 -0700270 int[] returnArray = new int[mContextHubInfo.length];
Peng Xu9ff7d222016-02-11 13:02:05 -0800271
Ashutosh Joshi1d941812017-03-09 15:21:24 -0800272 Log.d(TAG, "System supports " + returnArray.length + " hubs");
Peng Xu9ff7d222016-02-11 13:02:05 -0800273 for (int i = 0; i < returnArray.length; ++i) {
Ashutosh Joshi6239cc62016-04-04 16:19:29 -0700274 returnArray[i] = i;
Peng Xu9ff7d222016-02-11 13:02:05 -0800275 Log.d(TAG, String.format("Hub %s is mapped to %d",
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700276 mContextHubInfo[i].getName(), returnArray[i]));
Peng Xu9ff7d222016-02-11 13:02:05 -0800277 }
278
279 return returnArray;
280 }
281
282 @Override
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700283 public ContextHubInfo getContextHubInfo(int contextHubId) throws RemoteException {
destradaa8bad3fe2016-03-15 12:33:40 -0700284 checkPermissions();
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700285 if (!(contextHubId >= 0 && contextHubId < mContextHubInfo.length)) {
286 Log.e(TAG, "Invalid context hub handle " + contextHubId);
Peng Xu9ff7d222016-02-11 13:02:05 -0800287 return null; // null means fail
288 }
289
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700290 return mContextHubInfo[contextHubId];
291 }
292
293 /**
294 * Creates an internal load transaction callback to be used for old API clients
295 *
296 * @param contextHubId the ID of the hub to load the binary
297 * @param nanoAppBinary the binary to load
298 * @return the callback interface
299 */
300 private IContextHubTransactionCallback createLoadTransactionCallback(
301 int contextHubId, NanoAppBinary nanoAppBinary) {
302 return new IContextHubTransactionCallback.Stub() {
303 @Override
304 public void onTransactionComplete(int result) {
305 handleLoadResponseOldApi(contextHubId, result, nanoAppBinary);
306 }
307
308 @Override
309 public void onQueryResponse(int result, List<NanoAppState> nanoAppStateList) {
310 }
311 };
312 }
313
314 /**
315 * Creates an internal unload transaction callback to be used for old API clients
316 *
317 * @param contextHubId the ID of the hub to unload the nanoapp
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700318 * @return the callback interface
319 */
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800320 private IContextHubTransactionCallback createUnloadTransactionCallback(int contextHubId) {
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700321 return new IContextHubTransactionCallback.Stub() {
322 @Override
323 public void onTransactionComplete(int result) {
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800324 handleUnloadResponseOldApi(contextHubId, result);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700325 }
326
327 @Override
328 public void onQueryResponse(int result, List<NanoAppState> nanoAppStateList) {
329 }
330 };
331 }
332
333 /**
334 * Creates an internal query transaction callback to be used for old API clients
335 *
336 * @param contextHubId the ID of the hub to query
337 * @return the callback interface
338 */
339 private IContextHubTransactionCallback createQueryTransactionCallback(int contextHubId) {
340 return new IContextHubTransactionCallback.Stub() {
341 @Override
342 public void onTransactionComplete(int result) {
343 }
344
345 @Override
346 public void onQueryResponse(int result, List<NanoAppState> nanoAppStateList) {
347 byte[] data = {(byte) result};
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800348 onMessageReceiptOldApi(MSG_QUERY_NANO_APPS, contextHubId, OS_APP_INSTANCE, data);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700349 }
350 };
351 }
352
353 /**
354 * Adds a new transaction to the transaction manager queue
355 *
356 * @param transaction the transaction to add
357 * @return the result of adding the transaction
358 */
359 private int addTransaction(ContextHubServiceTransaction transaction) {
360 int result = Result.OK;
361 try {
362 mTransactionManager.addTransaction(transaction);
363 } catch (IllegalStateException e) {
364 Log.e(TAG, e.getMessage());
365 result = Result.TRANSACTION_PENDING; /* failed */
366 }
367
368 return result;
Peng Xu9ff7d222016-02-11 13:02:05 -0800369 }
370
371 @Override
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700372 public int loadNanoApp(int contextHubId, NanoApp app) throws RemoteException {
destradaa8bad3fe2016-03-15 12:33:40 -0700373 checkPermissions();
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700374 if (mContextHubProxy == null) {
375 return -1;
376 }
Peng Xu9ff7d222016-02-11 13:02:05 -0800377
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700378 if (!(contextHubId >= 0 && contextHubId < mContextHubInfo.length)) {
379 Log.e(TAG, "Invalid contextHubhandle " + contextHubId);
Ashutosh Joshi6239cc62016-04-04 16:19:29 -0700380 return -1;
Peng Xu9ff7d222016-02-11 13:02:05 -0800381 }
Jeff Sharkey49ca5292016-05-10 12:54:45 -0600382 if (app == null) {
Ashutosh Joshi1d941812017-03-09 15:21:24 -0800383 Log.e(TAG, "Invalid null app");
Jeff Sharkey49ca5292016-05-10 12:54:45 -0600384 return -1;
385 }
Peng Xu9ff7d222016-02-11 13:02:05 -0800386
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700387 // Create an internal IContextHubTransactionCallback for the old API clients
388 NanoAppBinary nanoAppBinary = new NanoAppBinary(app.getAppBinary());
389 IContextHubTransactionCallback onCompleteCallback =
390 createLoadTransactionCallback(contextHubId, nanoAppBinary);
Ashutosh Joshi54787a52016-04-27 11:19:16 -0700391
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700392 ContextHubServiceTransaction transaction = mTransactionManager.createLoadTransaction(
393 contextHubId, nanoAppBinary, onCompleteCallback);
Ashutosh Joshi54787a52016-04-27 11:19:16 -0700394
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700395 int result = addTransaction(transaction);
396 if (result != Result.OK) {
397 Log.e(TAG, "Failed to load nanoapp with error code " + result);
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700398 return -1;
399 }
Ashutosh Joshi11864402016-07-15 13:46:22 -0700400
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700401 // Do not add an entry to mNanoAppInstance Hash yet. The HAL may reject the app
402 return 0;
Peng Xu9ff7d222016-02-11 13:02:05 -0800403 }
404
destradaa8bad3fe2016-03-15 12:33:40 -0700405 @Override
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800406 public int unloadNanoApp(int nanoAppHandle) throws RemoteException {
destradaa8bad3fe2016-03-15 12:33:40 -0700407 checkPermissions();
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700408 if (mContextHubProxy == null) {
409 return -1;
410 }
411
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800412 NanoAppInstanceInfo info =
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800413 mNanoAppStateManager.getNanoAppInstanceInfo(nanoAppHandle);
Peng Xu9ff7d222016-02-11 13:02:05 -0800414 if (info == null) {
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800415 Log.e(TAG, "Cannot find nanoapp with handle " + nanoAppHandle);
416 return -1;
Peng Xu9ff7d222016-02-11 13:02:05 -0800417 }
418
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700419 int contextHubId = info.getContexthubId();
420 long nanoAppId = info.getAppId();
421 IContextHubTransactionCallback onCompleteCallback =
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800422 createUnloadTransactionCallback(contextHubId);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700423 ContextHubServiceTransaction transaction = mTransactionManager.createUnloadTransaction(
424 contextHubId, nanoAppId, onCompleteCallback);
Peng Xu9ff7d222016-02-11 13:02:05 -0800425
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700426 int result = addTransaction(transaction);
427 if (result != Result.OK) {
428 Log.e(TAG, "Failed to unload nanoapp with error code " + result);
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700429 return -1;
430 }
431
432 // Do not add an entry to mNanoAppInstance Hash yet. The HAL may reject the app
433 return 0;
destradaa8bad3fe2016-03-15 12:33:40 -0700434 }
Peng Xu9ff7d222016-02-11 13:02:05 -0800435
436 @Override
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800437 public NanoAppInstanceInfo getNanoAppInstanceInfo(int nanoAppHandle) throws RemoteException {
destradaa8bad3fe2016-03-15 12:33:40 -0700438 checkPermissions();
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800439
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800440 return mNanoAppStateManager.getNanoAppInstanceInfo(nanoAppHandle);
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -0800441 }
442
443 @Override
Peng Xu9ff7d222016-02-11 13:02:05 -0800444 public int[] findNanoAppOnHub(int hubHandle, NanoAppFilter filter) throws RemoteException {
destradaa8bad3fe2016-03-15 12:33:40 -0700445 checkPermissions();
Peng Xu9ff7d222016-02-11 13:02:05 -0800446
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800447 ArrayList<Integer> foundInstances = new ArrayList<>();
448 for (NanoAppInstanceInfo info : mNanoAppStateManager.getNanoAppInstanceInfoCollection()) {
Ashutosh Joshi6239cc62016-04-04 16:19:29 -0700449 if (filter.testMatch(info)) {
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800450 foundInstances.add(info.getHandle());
Peng Xu9ff7d222016-02-11 13:02:05 -0800451 }
452 }
453
454 int[] retArray = new int[foundInstances.size()];
455 for (int i = 0; i < foundInstances.size(); i++) {
456 retArray[i] = foundInstances.get(i).intValue();
457 }
458
Arthur Ishiguroafe52462017-11-22 15:18:54 -0800459 if (retArray.length == 0) {
460 Log.d(TAG, "No nanoapps found on hub ID " + hubHandle + " using NanoAppFilter: "
461 + filter);
462 }
463
Peng Xu9ff7d222016-02-11 13:02:05 -0800464 return retArray;
Ashutosh Joshi1d1ac542016-01-18 17:19:27 -0800465 }
466
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700467 /**
468 * Performs a query at the specified hub.
469 *
470 * This method should only be invoked internally by the service, either to update the service
471 * cache or as a result of an explicit query requested by a client through the sendMessage API.
472 *
473 * @param contextHubId the ID of the hub to do the query
474 * @return the result of the query
475 */
476 private int queryNanoAppsInternal(int contextHubId) {
477 if (mContextHubProxy == null) {
478 return Result.UNKNOWN_FAILURE;
479 }
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700480
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700481 IContextHubTransactionCallback onCompleteCallback =
482 createQueryTransactionCallback(contextHubId);
483 ContextHubServiceTransaction transaction = mTransactionManager.createQueryTransaction(
484 contextHubId, onCompleteCallback);
485
486 return addTransaction(transaction);
487 }
488
489 @Override
490 public int sendMessage(
491 int hubHandle, int nanoAppHandle, ContextHubMessage msg) throws RemoteException {
492 checkPermissions();
493 if (mContextHubProxy == null) {
494 return -1;
495 }
496 if (msg == null) {
497 Log.e(TAG, "ContextHubMessage cannot be null");
498 return -1;
499 }
500 if (msg.getData() == null) {
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800501 Log.e(TAG, "ContextHubMessage message body cannot be null");
502 return -1;
503 }
504 if (!mDefaultClientMap.containsKey(hubHandle)) {
505 Log.e(TAG, "Hub with ID " + hubHandle + " does not exist");
Jeff Sharkey49ca5292016-05-10 12:54:45 -0600506 return -1;
507 }
508
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800509 boolean success = false;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700510 if (nanoAppHandle == OS_APP_INSTANCE) {
511 if (msg.getMsgType() == MSG_QUERY_NANO_APPS) {
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800512 success = (queryNanoAppsInternal(hubHandle) == Result.OK);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700513 } else {
514 Log.e(TAG, "Invalid OS message params of type " + msg.getMsgType());
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700515 }
516 } else {
517 NanoAppInstanceInfo info = getNanoAppInstanceInfo(nanoAppHandle);
518 if (info != null) {
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800519 NanoAppMessage message = NanoAppMessage.createMessageToNanoApp(
520 info.getAppId(), msg.getMsgType(), msg.getData());
Peng Xu9ff7d222016-02-11 13:02:05 -0800521
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800522 IContextHubClient client = mDefaultClientMap.get(hubHandle);
523 success = (client.sendMessageToNanoApp(message) ==
524 ContextHubTransaction.TRANSACTION_SUCCESS);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700525 } else {
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800526 Log.e(TAG, "Failed to send nanoapp message - nanoapp with handle "
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700527 + nanoAppHandle + " does not exist.");
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700528 }
529 }
530
Arthur Ishiguroebb0e862017-11-17 14:55:32 -0800531 return success ? 0 : -1;
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700532 }
533
534 /**
535 * Handles a unicast or broadcast message from a nanoapp.
536 *
537 * @param contextHubId the ID of the hub the message came from
538 * @param message the message contents
539 */
540 private void handleClientMessageCallback(int contextHubId, ContextHubMsg message) {
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800541 mClientManager.onMessageFromNanoApp(contextHubId, message);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700542 }
543
544 /**
545 * A helper function to handle a load response from the Context Hub for the old API.
546 *
547 * TODO(b/69270990): Remove this once the old APIs are obsolete.
548 */
549 private void handleLoadResponseOldApi(
550 int contextHubId, int result, NanoAppBinary nanoAppBinary) {
551 if (nanoAppBinary == null) {
552 Log.e(TAG, "Nanoapp binary field was null for a load transaction");
553 return;
554 }
555
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700556 byte[] data = new byte[5];
557 data[0] = (byte) result;
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800558 int nanoAppHandle = mNanoAppStateManager.getNanoAppHandle(
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800559 contextHubId, nanoAppBinary.getNanoAppId());
Arthur Ishiguro2fc5a4b2017-12-11 15:15:44 -0800560 ByteBuffer.wrap(data, 1, 4).order(ByteOrder.nativeOrder()).putInt(nanoAppHandle);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700561
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800562 onMessageReceiptOldApi(MSG_LOAD_NANO_APP, contextHubId, OS_APP_INSTANCE, data);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700563 }
564
565 /**
566 * A helper function to handle an unload response from the Context Hub for the old API.
567 *
568 * TODO(b/69270990): Remove this once the old APIs are obsolete.
569 */
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800570 private void handleUnloadResponseOldApi(int contextHubId, int result) {
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700571 byte[] data = new byte[1];
572 data[0] = (byte) result;
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800573 onMessageReceiptOldApi(MSG_UNLOAD_NANO_APP, contextHubId, OS_APP_INSTANCE, data);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700574 }
575
576 /**
577 * Handles a transaction response from a Context Hub.
578 *
579 * @param contextHubId the ID of the hub the response came from
580 * @param transactionId the ID of the transaction
581 * @param result the result of the transaction reported by the hub
582 */
583 private void handleTransactionResultCallback(int contextHubId, int transactionId, int result) {
584 mTransactionManager.onTransactionResponse(transactionId, result);
585 }
586
587 /**
588 * Handles an asynchronous event from a Context Hub.
589 *
590 * @param contextHubId the ID of the hub the response came from
591 * @param eventType the type of the event as defined in Context Hub HAL AsyncEventType
592 */
593 private void handleHubEventCallback(int contextHubId, int eventType) {
594 if (eventType == AsyncEventType.RESTARTED) {
595 mTransactionManager.onHubReset();
596 queryNanoAppsInternal(contextHubId);
597
Arthur Ishiguro6d47c542017-11-17 15:49:07 -0800598 mClientManager.onHubReset(contextHubId);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700599 } else {
600 Log.i(TAG, "Received unknown hub event (hub ID = " + contextHubId + ", type = "
601 + eventType + ")");
602 }
603 }
604
605 /**
606 * Handles an asynchronous abort event of a nanoapp.
607 *
608 * @param contextHubId the ID of the hub that the nanoapp aborted in
609 * @param nanoAppId the ID of the aborted nanoapp
610 * @param abortCode the nanoapp-specific abort code
611 */
612 private void handleAppAbortCallback(int contextHubId, long nanoAppId, int abortCode) {
613 // TODO(b/31049861): Implement this
614 }
615
616 /**
617 * Handles a query response from a Context Hub.
618 *
619 * @param contextHubId the ID of the hub of the response
620 * @param nanoAppInfoList the list of loaded nanoapps
621 */
622 private void handleQueryAppsCallback(int contextHubId, List<HubAppInfo> nanoAppInfoList) {
623 List<NanoAppState> nanoAppStateList =
624 ContextHubServiceUtil.createNanoAppStateList(nanoAppInfoList);
625
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800626 mNanoAppStateManager.updateCache(contextHubId, nanoAppInfoList);
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700627 mTransactionManager.onQueryResponse(nanoAppStateList);
628 }
629
630 /**
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800631 * @param contextHubId the hub ID to validate
632 * @return {@code true} if the ID represents that of an available hub, {@code false} otherwise
633 */
634 private boolean isValidContextHubId(int contextHubId) {
635 for (ContextHubInfo hubInfo : mContextHubInfo) {
636 if (hubInfo.getId() == contextHubId) {
637 return true;
638 }
639 }
640
641 return false;
642 }
643
644 /**
645 * Creates and registers a client at the service for the specified Context Hub.
646 *
647 * @param clientCallback the client interface to register with the service
648 * @param contextHubId the ID of the hub this client is attached to
649 * @return the generated client interface, null if registration was unsuccessful
650 *
651 * @throws IllegalArgumentException if contextHubId is not a valid ID
652 * @throws IllegalStateException if max number of clients have already registered
653 * @throws NullPointerException if clientCallback is null
654 */
655 @Override
656 public IContextHubClient createClient(
657 IContextHubClientCallback clientCallback, int contextHubId) throws RemoteException {
658 checkPermissions();
659 if (!isValidContextHubId(contextHubId)) {
660 throw new IllegalArgumentException("Invalid context hub ID " + contextHubId);
661 }
662 if (clientCallback == null) {
663 throw new NullPointerException("Cannot register client with null callback");
664 }
665
666 return mClientManager.registerClient(clientCallback, contextHubId);
667 }
668
Arthur Ishiguroe1ade432017-11-27 10:45:33 -0800669 /**
670 * Loads a nanoapp binary at the specified Context hub.
671 *
672 * @param contextHubId the ID of the hub to load the binary
673 * @param transactionCallback the client-facing transaction callback interface
674 * @param nanoAppBinary the binary to load
675 *
676 * @throws RemoteException
677 */
678 @Override
679 public void loadNanoAppOnHub(
680 int contextHubId, IContextHubTransactionCallback transactionCallback,
681 NanoAppBinary nanoAppBinary) throws RemoteException {
682 checkPermissions();
Arthur Ishiguro4493e142017-11-27 16:26:34 -0800683 if (!checkHalProxyAndContextHubId(
684 contextHubId, transactionCallback, ContextHubTransaction.TYPE_LOAD_NANOAPP)) {
Arthur Ishiguroe1ade432017-11-27 10:45:33 -0800685 return;
686 }
687 if (nanoAppBinary == null) {
688 Log.e(TAG, "NanoAppBinary cannot be null in loadNanoAppOnHub");
689 transactionCallback.onTransactionComplete(
690 ContextHubTransaction.TRANSACTION_FAILED_BAD_PARAMS);
691 return;
692 }
693
694 ContextHubServiceTransaction transaction = mTransactionManager.createLoadTransaction(
695 contextHubId, nanoAppBinary, transactionCallback);
Arthur Ishiguroe1ade432017-11-27 10:45:33 -0800696 addTransaction(transaction);
697 }
698
699 /**
700 * Unloads a nanoapp from the specified Context Hub.
701 *
702 * @param contextHubId the ID of the hub to unload the nanoapp
703 * @param transactionCallback the client-facing transaction callback interface
704 * @param nanoAppId the ID of the nanoapp to unload
705 *
706 * @throws RemoteException
707 */
708 @Override
709 public void unloadNanoAppFromHub(
710 int contextHubId, IContextHubTransactionCallback transactionCallback, long nanoAppId)
711 throws RemoteException {
712 checkPermissions();
Arthur Ishiguro4493e142017-11-27 16:26:34 -0800713 if (!checkHalProxyAndContextHubId(
714 contextHubId, transactionCallback, ContextHubTransaction.TYPE_UNLOAD_NANOAPP)) {
Arthur Ishiguroe1ade432017-11-27 10:45:33 -0800715 return;
716 }
717
718 ContextHubServiceTransaction transaction = mTransactionManager.createUnloadTransaction(
719 contextHubId, nanoAppId, transactionCallback);
Arthur Ishiguro4493e142017-11-27 16:26:34 -0800720 addTransaction(transaction);
721 }
Arthur Ishiguroe1ade432017-11-27 10:45:33 -0800722
Arthur Ishiguro4493e142017-11-27 16:26:34 -0800723 /**
724 * Queries for a list of nanoapps from the specified Context hub.
725 *
726 * @param contextHubId the ID of the hub to query
727 * @param transactionCallback the client-facing transaction callback interface
728 *
729 * @throws RemoteException
730 */
731 @Override
732 public void queryNanoApps(int contextHubId, IContextHubTransactionCallback transactionCallback)
733 throws RemoteException {
734 checkPermissions();
735 if (!checkHalProxyAndContextHubId(
736 contextHubId, transactionCallback, ContextHubTransaction.TYPE_QUERY_NANOAPPS)) {
737 return;
738 }
739
740 ContextHubServiceTransaction transaction =
741 mTransactionManager.createQueryTransaction(contextHubId, transactionCallback);
Arthur Ishiguroe1ade432017-11-27 10:45:33 -0800742 addTransaction(transaction);
743 }
744
Ashutosh Joshi6239cc62016-04-04 16:19:29 -0700745 @Override
746 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600747 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Ashutosh Joshi6239cc62016-04-04 16:19:29 -0700748
749 pw.println("Dumping ContextHub Service");
750
751 pw.println("");
752 // dump ContextHubInfo
753 pw.println("=================== CONTEXT HUBS ====================");
754 for (int i = 0; i < mContextHubInfo.length; i++) {
755 pw.println("Handle " + i + " : " + mContextHubInfo[i].toString());
756 }
757 pw.println("");
758 pw.println("=================== NANOAPPS ====================");
759 // Dump nanoAppHash
Arthur Ishigurofb9e4c72017-11-21 15:33:21 -0800760 for (NanoAppInstanceInfo info : mNanoAppStateManager.getNanoAppInstanceInfoCollection()) {
761 pw.println(info);
Ashutosh Joshi6239cc62016-04-04 16:19:29 -0700762 }
763
764 // dump eventLog
765 }
766
destradaa8bad3fe2016-03-15 12:33:40 -0700767 private void checkPermissions() {
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800768 ContextHubServiceUtil.checkPermissions(mContext);
destradaa8bad3fe2016-03-15 12:33:40 -0700769 }
Ashutosh Joshi2c697fb2016-04-01 20:48:13 +0000770
Arthur Ishiguro4e39aa12017-11-14 14:59:08 -0800771 private int onMessageReceiptOldApi(int msgType, int hubHandle, int appInstance, byte[] data) {
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700772 if (data == null) {
773 return -1;
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700774 }
Ashutosh Joshi1d941812017-03-09 15:21:24 -0800775
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700776 int msgVersion = 0;
destradaa78cebca2016-04-14 18:40:14 -0700777 int callbacksCount = mCallbacksList.beginBroadcast();
Ashutosh Joshi1d941812017-03-09 15:21:24 -0800778 Log.d(TAG, "Sending message " + msgType + " version " + msgVersion + " from hubHandle " +
Arthur Ishiguro7a23a962017-11-01 10:52:28 -0700779 hubHandle + ", appInstance " + appInstance + ", callBackCount " + callbacksCount);
Ashutosh Joshi1d941812017-03-09 15:21:24 -0800780
destradaa78cebca2016-04-14 18:40:14 -0700781 if (callbacksCount < 1) {
782 Log.v(TAG, "No message callbacks registered.");
783 return 0;
784 }
Ashutosh Joshi54787a52016-04-27 11:19:16 -0700785
Ashutosh Joshi1d941812017-03-09 15:21:24 -0800786 ContextHubMessage msg = new ContextHubMessage(msgType, msgVersion, data);
destradaa78cebca2016-04-14 18:40:14 -0700787 for (int i = 0; i < callbacksCount; ++i) {
788 IContextHubCallback callback = mCallbacksList.getBroadcastItem(i);
789 try {
Ashutosh Joshi1d941812017-03-09 15:21:24 -0800790 callback.onMessageReceipt(hubHandle, appInstance, msg);
destradaa78cebca2016-04-14 18:40:14 -0700791 } catch (RemoteException e) {
792 Log.i(TAG, "Exception (" + e + ") calling remote callback (" + callback + ").");
793 continue;
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700794 }
795 }
destradaa78cebca2016-04-14 18:40:14 -0700796 mCallbacksList.finishBroadcast();
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700797 return 0;
798 }
799
Arthur Ishiguro4493e142017-11-27 16:26:34 -0800800 /**
801 * Validates the HAL proxy state and context hub ID to see if we can start the transaction.
802 *
803 * @param contextHubId the ID of the hub to start the transaction
804 * @param callback the client transaction callback interface
805 * @param transactionType the type of the transaction
806 *
807 * @return {@code true} if mContextHubProxy and contextHubId is valid, {@code false} otherwise
808 */
809 private boolean checkHalProxyAndContextHubId(
810 int contextHubId, IContextHubTransactionCallback callback,
811 @ContextHubTransaction.Type int transactionType) {
812 if (mContextHubProxy == null) {
813 try {
814 callback.onTransactionComplete(
815 ContextHubTransaction.TRANSACTION_FAILED_HAL_UNAVAILABLE);
816 } catch (RemoteException e) {
817 Log.e(TAG, "RemoteException while calling onTransactionComplete", e);
818 }
819 return false;
820 }
821 if (!isValidContextHubId(contextHubId)) {
822 Log.e(TAG, "Cannot start "
823 + ContextHubTransaction.typeToString(transactionType, false /* upperCase */)
824 + " transaction for invalid hub ID " + contextHubId);
825 try {
826 callback.onTransactionComplete(ContextHubTransaction.TRANSACTION_FAILED_BAD_PARAMS);
827 } catch (RemoteException e) {
828 Log.e(TAG, "RemoteException while calling onTransactionComplete", e);
829 }
830 return false;
831 }
832
833 return true;
834 }
Ashutosh Joshib741e3b2016-03-29 09:19:56 -0700835}