]> git.scottworley.com Git - tattlekey/blob - client/press.c
1c8ce9f1ae2cb4e2318a90192ccbe0ec0150e245
[tattlekey] / client / press.c
1 #include "press.h"
2 #include "blink.h"
3
4 static uint32_t next_send(press_t *s) {
5 return s->timestamp + (1 << s->send_count) - 1;
6 }
7
8 static bool next_send_less_than(void *user_data, pheap_node_id_t a,
9 pheap_node_id_t b) {
10 press_t *presses = (press_t *)user_data;
11 return next_send(&presses[a]) < next_send(&presses[b]);
12 }
13
14 static void *xcalloc(size_t nmemb, size_t size) {
15 void *p = calloc(nmemb, size);
16 if (p == NULL)
17 signal_error_by_blinking();
18 return p;
19 }
20
21 press_pile_t *create_press_pile() {
22 press_pile_t *pp = (press_pile_t *)xcalloc(1, sizeof(press_pile_t));
23 pp->presses = (press_t *)xcalloc(PICO_PHEAP_MAX_ENTRIES, sizeof(press_t));
24 pp->sleeps_heap =
25 ph_create(PICO_PHEAP_MAX_ENTRIES, next_send_less_than, pp->presses);
26 if (pp->sleeps_heap == NULL)
27 signal_error_by_blinking();
28 return pp;
29 }
30
31 void add_press(press_pile_t *pp, press_t *press) {
32 pheap_node_id_t i = ph_new_node(pp->sleeps_heap);
33 if (i == 0) {
34 /* TODO: Don't drop new presses just because sleeps_heap is full of old
35 * presses. */
36 return;
37 }
38 pp->presses[i] = *press;
39 ph_insert_node(pp->sleeps_heap, i);
40 }
41
42 int32_t next_scheduled_send(press_pile_t *pp) {
43 pheap_node_id_t i = ph_peek_head(pp->sleeps_heap);
44 if (i == 0)
45 return -1;
46 return next_send(&pp->presses[i]);
47 }
48
49 bool get_press_due_for_resend(press_pile_t *pp, uint32_t now, press_t *press) {
50 pheap_node_id_t i = ph_peek_head(pp->sleeps_heap);
51 if (i == 0 || next_send(&pp->presses[i]) > now)
52 return false;
53 if (ph_remove_head(pp->sleeps_heap, true) != i)
54 signal_error_by_blinking();
55 *press = pp->presses[i];
56 return true;
57 }