summaryrefslogtreecommitdiff
path: root/cras/src/server/polled_interval_checker.c
blob: 37f93684e8ea2e164a3efb68a95bec84e3f44411 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* Copyright 2018 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "cras_util.h"
#include "polled_interval_checker.h"

struct polled_interval {
	struct timespec last_interval_start_ts;
	int interval_sec;
};

static struct timespec now;

static inline int
get_sec_since_last_active(const struct timespec *last_active_ts)
{
	struct timespec diff;
	subtract_timespecs(&now, last_active_ts, &diff);
	return diff.tv_sec;
}

void pic_update_current_time()
{
	clock_gettime(CLOCK_MONOTONIC_RAW, &now);
}

struct polled_interval *pic_polled_interval_create(int interval_sec)
{
	struct polled_interval *pi;
	pi = malloc(sizeof(*pi));
	pi->last_interval_start_ts = now;
	pi->interval_sec = interval_sec;
	return pi;
}

void pic_polled_interval_destroy(struct polled_interval **interval)
{
	free(*interval);
	*interval = NULL;
}

int pic_interval_elapsed(const struct polled_interval *pi)
{
	return get_sec_since_last_active(&pi->last_interval_start_ts) >=
	       pi->interval_sec;
}

void pic_interval_reset(struct polled_interval *pi)
{
	pi->last_interval_start_ts = now;
}