San Mehat | 1441e76 | 2009-05-07 11:37:10 -0700 | [diff] [blame^] | 1 | #include <errno.h> |
| 2 | #include <pthread.h> |
| 3 | |
| 4 | #define LOG_TAG "WifiScanner" |
| 5 | #include <cutils/log.h> |
| 6 | |
| 7 | #include "WifiScanner.h" |
| 8 | #include "Supplicant.h" |
| 9 | |
| 10 | extern "C" int pthread_cancel(pthread_t thread); |
| 11 | |
| 12 | WifiScanner::WifiScanner(Supplicant *suppl, int period) { |
| 13 | mSuppl = suppl; |
| 14 | mPeriod = period; |
| 15 | mActive = false; |
| 16 | mWorkerRunning = false; |
| 17 | mAbortRequest = false; |
| 18 | pthread_mutex_init(&mAbortRequestLock, NULL); |
| 19 | pthread_mutex_init(&mWorkerLock, NULL); |
| 20 | } |
| 21 | |
| 22 | int WifiScanner::startPeriodicScan(bool active) { |
| 23 | mActive = active; |
| 24 | |
| 25 | pthread_mutex_lock(&mWorkerLock); |
| 26 | if (mWorkerRunning) { |
| 27 | errno = EBUSY; |
| 28 | return -1; |
| 29 | } |
| 30 | |
| 31 | pthread_attr_t attr; |
| 32 | pthread_attr_init(&attr); |
| 33 | pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); |
| 34 | |
| 35 | if (pthread_create(&mWorker, &attr, WifiScanner::threadStart, this)) |
| 36 | return -1; |
| 37 | |
| 38 | return 0; |
| 39 | } |
| 40 | |
| 41 | void *WifiScanner::threadStart(void *obj) { |
| 42 | WifiScanner *me = reinterpret_cast<WifiScanner *>(obj); |
| 43 | me->run(); |
| 44 | pthread_exit(NULL); |
| 45 | return NULL; |
| 46 | } |
| 47 | |
| 48 | void WifiScanner::threadCleanup(void *obj) { |
| 49 | WifiScanner *me = reinterpret_cast<WifiScanner *>(obj); |
| 50 | |
| 51 | me->mWorkerRunning = false; |
| 52 | pthread_mutex_unlock(&me->mWorkerLock); |
| 53 | |
| 54 | if (me->mAbortRequest) { |
| 55 | me->mAbortRequest = false; |
| 56 | pthread_mutex_unlock(&me->mAbortRequestLock); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | int WifiScanner::stopPeriodicScan() { |
| 61 | pthread_mutex_lock(&mAbortRequestLock); |
| 62 | pthread_mutex_lock(&mWorkerLock); |
| 63 | if (mWorkerRunning) |
| 64 | mAbortRequest = true; |
| 65 | pthread_mutex_unlock(&mWorkerLock); |
| 66 | pthread_mutex_unlock(&mAbortRequestLock); |
| 67 | |
| 68 | return 0; |
| 69 | } |
| 70 | |
| 71 | void WifiScanner::run() { |
| 72 | LOGD("Thread started"); |
| 73 | |
| 74 | mWorkerRunning = true; |
| 75 | pthread_cleanup_push(WifiScanner::threadCleanup, this); |
| 76 | pthread_mutex_unlock(&mWorkerLock); |
| 77 | |
| 78 | while(1) { |
| 79 | LOGD("Triggering periodic scan"); |
| 80 | if (mSuppl->triggerScan(mActive)) { |
| 81 | LOGW("Error triggering scan (%s)", strerror(errno)); |
| 82 | } |
| 83 | |
| 84 | sleep(mPeriod); |
| 85 | pthread_mutex_lock(&mAbortRequestLock); |
| 86 | if (mAbortRequest) { |
| 87 | LOGD("Abort request!"); |
| 88 | goto out; |
| 89 | } |
| 90 | pthread_mutex_unlock(&mAbortRequestLock); |
| 91 | } |
| 92 | |
| 93 | out: |
| 94 | pthread_cleanup_pop(1); |
| 95 | pthread_mutex_unlock(&mWorkerLock); |
| 96 | } |