1 /******************************************************************************
2  *
3  *  Copyright (C) 2014 Google, Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #include <gtest/gtest.h>
20 #include <hardware/bluetooth.h>
21 #include <unistd.h>
22 
23 #include "AlarmTestHarness.h"
24 
25 extern "C" {
26 #include "alarm.h"
27 #include "allocation_tracker.h"
28 }
29 
30 static timer_t timer;
31 static alarm_cb saved_callback;
32 static void *saved_data;
33 static AlarmTestHarness *current_harness;
34 
timer_callback(void *)35 static void timer_callback(void *) {
36   saved_callback(saved_data);
37 }
38 
SetUp()39 void AlarmTestHarness::SetUp() {
40   AllocationTestHarness::SetUp();
41 
42   current_harness = this;
43   TIMER_INTERVAL_FOR_WAKELOCK_IN_MS = 100;
44   lock_count = 0;
45 
46   struct sigevent sigevent;
47   memset(&sigevent, 0, sizeof(sigevent));
48   sigevent.sigev_notify = SIGEV_THREAD;
49   sigevent.sigev_notify_function = (void (*)(union sigval))timer_callback;
50   sigevent.sigev_value.sival_ptr = NULL;
51   timer_create(CLOCK_BOOTTIME, &sigevent, &timer);
52 }
53 
TearDown()54 void AlarmTestHarness::TearDown() {
55   alarm_cleanup();
56   timer_delete(timer);
57   AllocationTestHarness::TearDown();
58 }
59 
set_wake_alarm(uint64_t delay_millis,bool,alarm_cb cb,void * data)60 static bool set_wake_alarm(uint64_t delay_millis, bool, alarm_cb cb, void *data) {
61   saved_callback = cb;
62   saved_data = data;
63 
64   struct itimerspec wakeup_time;
65   memset(&wakeup_time, 0, sizeof(wakeup_time));
66   wakeup_time.it_value.tv_sec = (delay_millis / 1000);
67   wakeup_time.it_value.tv_nsec = (delay_millis % 1000) * 1000000LL;
68   timer_settime(timer, 0, &wakeup_time, NULL);
69   return true;
70 }
71 
acquire_wake_lock(const char *)72 static int acquire_wake_lock(const char *) {
73   if (!current_harness->lock_count)
74     current_harness->lock_count = 1;
75   return BT_STATUS_SUCCESS;
76 }
77 
release_wake_lock(const char *)78 static int release_wake_lock(const char *) {
79   if (current_harness->lock_count)
80     current_harness->lock_count = 0;
81   return BT_STATUS_SUCCESS;
82 }
83 
84 static bt_os_callouts_t stub = {
85   sizeof(bt_os_callouts_t),
86   set_wake_alarm,
87   acquire_wake_lock,
88   release_wake_lock,
89 };
90 
91 bt_os_callouts_t *bt_os_callouts = &stub;
92 
93