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 <assert.h> 20 21 #include "osi/include/allocator.h" 22 #include "osi/include/osi.h" 23 #include "osi/include/non_repeating_timer.h" 24 25 struct non_repeating_timer_t { 26 alarm_t *alarm; 27 period_ms_t duration; 28 alarm_callback_t callback; 29 void *data; 30 }; 31 32 non_repeating_timer_t *non_repeating_timer_new(period_ms_t duration, alarm_callback_t cb, void *data) { 33 assert(cb != NULL); 34 35 non_repeating_timer_t *ret = osi_calloc(sizeof(non_repeating_timer_t)); 36 37 ret->alarm = alarm_new(); 38 if (!ret->alarm) 39 goto error; 40 41 ret->duration = duration; 42 ret->callback = cb; 43 ret->data = data; 44 45 return ret; 46 error:; 47 non_repeating_timer_free(ret); 48 return NULL; 49 } 50 51 void non_repeating_timer_free(non_repeating_timer_t *timer) { 52 if (!timer) 53 return; 54 55 alarm_free(timer->alarm); 56 osi_free(timer); 57 } 58 59 void non_repeating_timer_restart(non_repeating_timer_t *timer) { 60 non_repeating_timer_restart_if(timer, true); 61 } 62 63 void non_repeating_timer_restart_if(non_repeating_timer_t *timer, bool condition) { 64 assert(timer != NULL); 65 if (condition) 66 alarm_set(timer->alarm, timer->duration, timer->callback, timer->data); 67 else 68 non_repeating_timer_cancel(timer); 69 } 70 71 void non_repeating_timer_cancel(non_repeating_timer_t *timer) { 72 assert(timer != NULL); 73 alarm_cancel(timer->alarm); 74 } 75