Merge branch 'master' into windows-port
[platform/upstream/iotivity.git] / resource / csdk / connectivity / util / src / camanager / android / caleconnectionmanager.c
1 /* ****************************************************************
2  *
3  * Copyright 2016 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 #include <jni.h>
22 #include "logger.h"
23 #include "cautilinterface.h"
24 #include "camanagerleinterface.h"
25 #include "camanagerleutil.h"
26 #include "caleautoconnector.h"
27 #include "cacommon.h"
28 #include "cacommonutil.h"
29 #include "camanagerdevice.h"
30 #include "caleclient.h"
31 #include "caleutils.h"
32
33 #define TAG "OIC_CA_MANAGER_LE"
34
35 static const jint SUPPORT_ADNROID_API_LEVEL = 18;
36 static const jint AUTH_FAIL = 5;
37 static const jint LINK_LOSS = 8;
38 static const jint ACCEPT_TIMEOUT_EXCEPTION = 16;
39 static const jint REMOTE_DISCONNECT = 19;
40 static const jint LOCAL_DISCONNECT = 22;
41 static const jint USER_REMOVED_BOND = 68;
42 static JavaVM *g_jvm = NULL;
43 static jobject g_context = NULL;
44 static jobject g_connectedDeviceSet = NULL;
45
46
47 CAResult_t CASetLEClientAutoConnectionDeviceInfo(const char* address)
48 {
49     OIC_LOG(DEBUG, TAG, "CASetClientAutoConnectionDeviceInfo");
50     VERIFY_NON_NULL(address, TAG, "address");
51
52     bool isAttached = false;
53     JNIEnv* env;
54     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
55     if (JNI_OK != res)
56     {
57         OIC_LOG(DEBUG, TAG, "AttachCurrentThread will be called for JNIEnv pointer");
58         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
59
60         if (JNI_OK != res)
61         {
62             OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
63             return CA_STATUS_FAILED;
64         }
65         isAttached = true;
66     }
67     OIC_LOG_V(DEBUG, TAG, "set [%s] for Auto Connection", address);
68
69     jstring jni_leAddress = (*env)->NewStringUTF(env, address);
70     if (!jni_leAddress)
71     {
72         OIC_LOG(ERROR, TAG, "jni_leAddress is null");
73         goto error_exit;
74     }
75
76     if (!CAManagerCheckBTAddress(env, jni_leAddress))
77     {
78         OIC_LOG(ERROR, TAG, "this address is not BT address string format");
79         goto error_exit;
80     }
81
82     // if there is target address in SharedPreference, it will be reset.
83     if (CAManagerIsConnectedDeviceAddress(env, g_context, jni_leAddress, g_connectedDeviceSet))
84     {
85         if (!CAManagerRemoveConnectedDeviceAddress(env, g_context, jni_leAddress,
86                                                    g_connectedDeviceSet))
87         {
88             OIC_LOG(ERROR, TAG, "Preference - remove has failed");
89         }
90         else
91         {
92             OIC_LOG(INFO, TAG, "Preference - remove success");
93         }
94     }
95
96     // it will be added new target address.
97     if (!CAManagerAddConnectedDeviceAddress(env, g_context, jni_leAddress, g_connectedDeviceSet))
98     {
99         OIC_LOG(ERROR, TAG, "Preference - putting has failed");
100     }
101     else
102     {
103         OIC_LOG(INFO, TAG, "Preference - putting success");
104     }
105
106     if (isAttached)
107     {
108         (*g_jvm)->DetachCurrentThread(g_jvm);
109     }
110
111     return CA_STATUS_OK;
112
113 error_exit:
114
115     if (isAttached)
116     {
117         (*g_jvm)->DetachCurrentThread(g_jvm);
118     }
119
120     return CA_STATUS_FAILED;
121 }
122
123 CAResult_t CAUnsetLEClientAutoConnectionDeviceInfo(const char* address)
124 {
125     OIC_LOG(DEBUG, TAG, "CAUnsetClientAutoConnectionDeviceInfo");
126     VERIFY_NON_NULL(address, TAG, "address");
127
128     bool isAttached = false;
129     JNIEnv* env;
130     jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
131     if (JNI_OK != res)
132     {
133         OIC_LOG(DEBUG, TAG, "AttachCurrentThread will be called for JNIEnv pointer");
134         res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
135
136         if (JNI_OK != res)
137         {
138             OIC_LOG(ERROR, TAG, "AttachCurrentThread has failed");
139             return CA_STATUS_FAILED;
140         }
141         isAttached = true;
142     }
143     OIC_LOG_V(DEBUG, TAG, "unset [%s] for Auto Connection", address);
144
145     jstring jni_leAddress = (*env)->NewStringUTF(env, address);
146     if (!jni_leAddress)
147     {
148         OIC_LOG(ERROR, TAG, "jni_leAddress is null");
149         goto error_exit;
150     }
151
152     if (!CAManagerCheckBTAddress(env, jni_leAddress))
153     {
154         OIC_LOG(ERROR, TAG, "this address is not BT address string format");
155         goto error_exit;
156     }
157
158     // if there is target address in SharedPreference, it will be removed
159     if (CAManagerIsConnectedDeviceAddress(env, g_context, jni_leAddress, g_connectedDeviceSet))
160     {
161         if (!CAManagerRemoveConnectedDeviceAddress(env, g_context, jni_leAddress,
162                                                    g_connectedDeviceSet))
163         {
164             OIC_LOG(ERROR, TAG, "Preference - remove has failed");
165         }
166         else
167         {
168             OIC_LOG(INFO, TAG, "Preference - remove success");
169         }
170     }
171
172     // remove target device for auto connection
173     CAResult_t ret = CAManagerRemoveACData(env, jni_leAddress);
174     if (CA_STATUS_OK != ret)
175     {
176         OIC_LOG(ERROR, TAG, "CAManagerRemoveACData has failed");
177     }
178
179     if (isAttached)
180     {
181         (*g_jvm)->DetachCurrentThread(g_jvm);
182     }
183
184     return ret;
185
186 error_exit:
187
188     if (isAttached)
189     {
190         (*g_jvm)->DetachCurrentThread(g_jvm);
191     }
192
193     return CA_STATUS_FAILED;
194 }
195
196 CAResult_t CAManagerLEClientInitialize(JNIEnv *env, JavaVM *jvm, jobject context)
197 {
198     OIC_LOG(DEBUG, TAG, "CAManagerClientInitialize");
199     VERIFY_NON_NULL(env, TAG, "env");
200     VERIFY_NON_NULL(jvm, TAG, "jvm");
201     VERIFY_NON_NULL(context, TAG, "context");
202
203     jint jni_int_sdk = CALEGetBuildVersion(env);
204     if (jni_int_sdk < SUPPORT_ADNROID_API_LEVEL)
205     {
206         OIC_LOG_V(ERROR, TAG, "it is not supported (%d)", jni_int_sdk);
207         return CA_STATUS_FAILED;
208     }
209
210     g_jvm = jvm;
211     g_context = (*env)->NewGlobalRef(env, context);;
212
213     CAManagerInitMutexVaraibles();
214     CAManagerInitLEAutoConnection();
215     CAManagerCreateACDataList();
216
217     // get last connected device list
218     jobject set = NULL;
219     set = CAManagerGetConnectedDeviceAddress(env, g_context);
220     if (!set)
221     {
222         // create new set<String> object
223         set = CAManagerCreateSetString(env);
224         if (!set)
225         {
226             OIC_LOG(ERROR, TAG, "CAManagerCreateSetString has failed");
227             return CA_STATUS_FAILED;
228         }
229         OIC_LOG(DEBUG, TAG, "created new SetString");
230     }
231     else
232     {
233         OIC_LOG(DEBUG, TAG, "get previous Set<String> object");
234     }
235
236     g_connectedDeviceSet = (jobject)(*env)->NewGlobalRef(env, set);
237     if (!g_connectedDeviceSet)
238     {
239         OIC_LOG(ERROR, TAG, "g_connectedDeviceSet is null");
240         return CA_STATUS_FAILED;
241     }
242
243     return CA_STATUS_OK;
244 }
245
246 CAResult_t CAManagerLEClientTerminate(JNIEnv *env)
247 {
248     OIC_LOG(DEBUG, TAG, "CAManagerClientTerminate");
249     VERIFY_NON_NULL(env, TAG, "env");
250
251     // stop gatt connection
252     CAResult_t res = CALEClientDisconnectAll(env);
253     if (CA_STATUS_OK != res)
254     {
255         OIC_LOG(ERROR, TAG, "CALEClientDisconnectAll has failed");
256     }
257
258     res = CAManagerRemoveAllACData(env);
259     if (CA_STATUS_OK != res)
260     {
261         OIC_LOG(ERROR, TAG, "CAManagerRemoveAllACData has failed");
262     }
263
264     CAManagerDestroyACDataList();
265     CAManagerTerminateLEAutoConnection();
266     CAManagerTerminateMutexVariables();
267
268     if (g_context)
269     {
270         (*env)->DeleteGlobalRef(env, g_context);
271         g_context = NULL;
272     }
273
274     if (g_connectedDeviceSet)
275     {
276         (*env)->DeleteGlobalRef(env, g_connectedDeviceSet);
277         g_connectedDeviceSet = NULL;
278     }
279
280     return res;
281 }
282
283 JNIEXPORT void JNICALL
284 Java_org_iotivity_ca_CaLeClientInterface_caManagerAdapterStateChangedCallback(
285         JNIEnv *env, jobject obj, jint state)
286 {
287     OIC_LOG_V(INFO, TAG, "caManagerAdapterStateChangedCallback - state %d", state);
288     VERIFY_NON_NULL_VOID(env, TAG, "env");
289     VERIFY_NON_NULL_VOID(obj, TAG, "obj");
290
291     jint state_on = CALEGetConstantsValue(env, CLASSPATH_BT_ADAPTER, "STATE_ON");
292     jint state_off = CALEGetConstantsValue(env, CLASSPATH_BT_ADAPTER, "STATE_OFF");
293     jint state_turning_off = CALEGetConstantsValue(env, CLASSPATH_BT_ADAPTER, "STATE_TURNING_OFF");
294
295     if (state_on == state)
296     {
297         OIC_LOG(DEBUG, TAG, "AdapterStateChangedCallback : state_on");
298
299         // when BT state is on. recovery flag has to be reset.
300         CAManagerSetBTRecovery(false);
301
302         // find target device for autoconnect
303         size_t length = CAManagerGetACDataLength();
304         OIC_LOG_V(DEBUG, TAG, "length of ACDataList : %d", length);
305         for (size_t idx = 0; idx < length; idx++)
306         {
307             jstring leAddress = CAManagerGetLEAddressFromACData(env, idx);
308             if (leAddress)
309             {
310                 CAResult_t res = CAManagerStartAutoConnection(env, leAddress);
311                 if (CA_STATUS_OK != res)
312                 {
313                     OIC_LOG(ERROR, TAG, "CAManagerStartAutoConnection has failed");
314                     return;
315                 }
316             }
317         }
318     }
319     else if (state_off == state)
320     {
321         OIC_LOG(DEBUG, TAG, "AdapterStateChangedCallback : state_off");
322
323         // reset isAutoConnecting flag for all target devices
324         size_t length = CAManagerGetACDataLength();
325         OIC_LOG_V(DEBUG, TAG, "length of ACDataList : %d", length);
326         for (size_t idx = 0; idx < length; idx++)
327         {
328             jstring address = CAManagerGetLEAddressFromACData(env, idx);
329             if (address)
330             {
331                 CAManagerSetAutoConnectingFlag(env, address, false);
332             }
333         }
334
335         // check whether BT recovery is needed or not
336         if (CAManagerIsRecoveryFlagSet())
337         {
338             CAManagerProcessRecovery(env, STATE_OFF);
339         }
340     }
341     else if (state_turning_off == state)
342     {
343         OIC_LOG(DEBUG, TAG, "AdapterStateChangedCallback : state_turning_off");
344     }
345     else
346     {
347         OIC_LOG(INFO, TAG, "AdapterStateChangedCallback state is not available");
348     }
349 }
350
351 JNIEXPORT void JNICALL
352 Java_org_iotivity_ca_CaLeClientInterface_caManagerBondStateChangedCallback(
353         JNIEnv *env, jobject obj, jobject device)
354 {
355     OIC_LOG(INFO, TAG, "caManagerBondStateChangedCallback");
356     // this callback is called by CaLeClientInterface
357     // only when bond state is changed from BOND_BONDED to BOND_NONE
358     OIC_LOG(DEBUG, TAG, "bond state is changed from BOND_BONDED to BOND_NONE");
359     VERIFY_NON_NULL_VOID(env, TAG, "env");
360     VERIFY_NON_NULL_VOID(obj, TAG, "obj");
361     VERIFY_NON_NULL_VOID(device, TAG, "device");
362
363     // get ble address from Bluetooth Device object
364     jstring jni_leAddress = CALEClientGetLEAddressFromBTDevice(env, device);
365     if (!jni_leAddress)
366     {
367         OIC_LOG(INFO, TAG, "unbonded : it isn't same device type");
368         return;
369     }
370
371     char* leAddress = (char*)(*env)->GetStringUTFChars(env, jni_leAddress, NULL);
372     if (!leAddress)
373     {
374         OIC_LOG(ERROR, TAG, "leAddress is null");
375         return;
376     }
377
378     // if there is no data, CAData will be created.
379     OIC_LOG_V(DEBUG, TAG, "bond none device : %s", leAddress);
380
381     CAResult_t res = CAManagerRemoveACData(env, jni_leAddress);
382     if (CA_STATUS_OK != res)
383     {
384         OIC_LOG(ERROR, TAG, "CAManagerRemoveACData has failed");
385     }
386
387     (*env)->ReleaseStringUTFChars(env, jni_leAddress, leAddress);
388
389     if (!CAManagerRemoveConnectedDeviceAddress(env, g_context, jni_leAddress,
390                                                g_connectedDeviceSet))
391     {
392         OIC_LOG(ERROR, TAG, "CAManagerRemoveConnectedDeviceAddress has failed");
393     }
394 }
395
396 JNIEXPORT void JNICALL
397 Java_org_iotivity_ca_CaLeClientInterface_caManagerLeGattConnectionStateChangeCB(
398         JNIEnv *env, jobject obj, jobject gatt, jint status, jint newState)
399 {
400     OIC_LOG_V(INFO, TAG, "caManagerLeGattConnectionStateChangeCB - status %d, newState %d",
401               status, newState);
402
403     VERIFY_NON_NULL_VOID(env, TAG, "env");
404     VERIFY_NON_NULL_VOID(obj, TAG, "obj");
405     VERIFY_NON_NULL_VOID(gatt, TAG, "gatt");
406
407     jint state_connected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE, "STATE_CONNECTED");
408     jint state_disconnected = CALEGetConstantsValue(env, CLASSPATH_BT_PROFILE, "STATE_DISCONNECTED");
409
410     jstring jni_address = CALEGetAddressFromGatt(env, gatt);
411     if (!jni_address)
412     {
413         OIC_LOG(ERROR, TAG, "CALEGetAddressFromGatt is null");
414         return;
415     }
416
417     char* address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
418     if (!address)
419     {
420         OIC_LOG(ERROR, TAG, "address is null");
421         (*env)->DeleteLocalRef(env, jni_address);
422         return;
423     }
424
425     OIC_LOG_V(DEBUG, TAG, "caManagerLeGattConnectionStateChangeCB - address [%s]", address);
426
427     if (GATT_SUCCESS == status && state_connected == newState) // le connected
428     {
429         OIC_LOG(DEBUG, TAG, "LE is connected");
430
431         CAResult_t res = CAManagerReadRemoteRssi(env, gatt);
432         if (CA_STATUS_OK != res)
433         {
434             OIC_LOG(ERROR, TAG, "CAManagerReadRemoteRssi has failed");
435             goto exit;
436         }
437     }
438     else if (state_disconnected == newState)// le disconnected
439     {
440         OIC_LOG(DEBUG, TAG, "LE is disconnected");
441
442         if (LINK_LOSS == status || REMOTE_DISCONNECT == status)
443         {
444             if (!CAManagerIsInACDataList(env, jni_address))
445             {
446                 OIC_LOG_V(DEBUG, TAG, "this[%s] is not target address for Auto Connection",
447                           address);
448                 goto exit;
449             }
450
451             CAManagerSetAutoConnectingFlag(env, jni_address, false);
452
453             CAResult_t res = CAManagerStartAutoConnection(env, jni_address);
454             if (CA_STATUS_OK != res)
455             {
456                 OIC_LOG(ERROR, TAG, "CAManagerStartAutoConnection has failed");
457                 goto exit;
458             }
459         }
460         else if (ACCEPT_TIMEOUT_EXCEPTION == status)
461         {
462             CAManagerProcessRecovery(env, START_RECOVERY);
463         }
464     }
465
466 exit:
467     (*env)->ReleaseStringUTFChars(env, jni_address, address);
468     (*env)->DeleteLocalRef(env, jni_address);
469 }
470
471 /*
472  * Class:     org_iotivity_ca_jar_caleinterface
473  * Method:    caManagerLeServicesDiscoveredCallback
474  * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
475  */
476 JNIEXPORT void JNICALL
477 Java_org_iotivity_ca_CaLeClientInterface_caManagerLeServicesDiscoveredCallback(JNIEnv *env,
478                                                                                jobject obj,
479                                                                                jobject gatt,
480                                                                                jint status)
481 {
482     OIC_LOG_V(INFO, TAG, "caManagerLeServicesDiscoveredCallback - status %d", status);
483     VERIFY_NON_NULL_VOID(env, TAG, "env");
484     VERIFY_NON_NULL_VOID(obj, TAG, "obj");
485     VERIFY_NON_NULL_VOID(gatt, TAG, "gatt");
486
487     if (GATT_SUCCESS == status)
488     {
489         if (!g_connectedDeviceSet)
490         {
491             OIC_LOG(ERROR, TAG, "g_connectedDeviceSet is null");
492             return;
493         }
494
495         jstring jni_address = CALEGetAddressFromGatt(env, gatt);
496         if (!jni_address)
497         {
498             OIC_LOG(ERROR, TAG, "CALEGetAddressFromGatt is null");
499             return;
500         }
501
502         char* address = (char*)(*env)->GetStringUTFChars(env, jni_address, NULL);
503         if (!address)
504         {
505             OIC_LOG(ERROR, TAG, "address is null");
506             (*env)->DeleteLocalRef(env, jni_address);
507             return;
508         }
509
510         OIC_LOG_V(DEBUG, TAG, "ServicesDiscovered device : %s", address);
511
512         if (CAManagerIsConnectedDeviceAddress(env, g_context, jni_address, g_connectedDeviceSet))
513         {
514             OIC_LOG(INFO, TAG, "AC list - the address will be added to ACData list");
515             CAManagerAddACData(env, jni_address);
516             CAManagerSetAutoConnectingFlag(env, jni_address, false);
517
518             // next connection will be requested with JNI_TRUE on autoConnect flag
519             // after first connection
520             CALEClientSetFlagToState(env, jni_address, CA_LE_AUTO_CONNECT_FLAG, JNI_TRUE);
521         }
522         else
523         {
524             OIC_LOG(DEBUG, TAG, "AC list - the address is not set to AutoConnect");
525         }
526
527         (*env)->ReleaseStringUTFChars(env, jni_address, address);
528         (*env)->DeleteLocalRef(env, jni_address);
529
530         OIC_LOG(INFO, TAG, "ServicesDiscovery is successful");
531     }
532     else
533     {
534         OIC_LOG(ERROR, TAG, "ServicesDiscovery has failed");
535     }
536 }
537
538 /*
539  * Class:     org_iotivity_ca_jar_caleinterface
540  * Method:    caManagerLeRemoteRssiCallback
541  * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
542  */
543 JNIEXPORT void JNICALL
544 Java_org_iotivity_ca_CaLeClientInterface_caManagerLeRemoteRssiCallback(JNIEnv *env,
545                                                                        jobject obj,
546                                                                        jobject gatt,
547                                                                        jint rssi,
548                                                                        jint status)
549 {
550     OIC_LOG_V(DEBUG, TAG, "caManagerLeRemoteRssiCallback - rssi : %d: ", rssi);
551     OIC_LOG_V(DEBUG, TAG, "caManagerLeRemoteRssiCallback - status : %d: ", status);
552     VERIFY_NON_NULL_VOID(env, TAG, "env");
553     VERIFY_NON_NULL_VOID(obj, TAG, "obj");
554     VERIFY_NON_NULL_VOID(gatt, TAG, "gatt");
555 }