]> git.scottworley.com Git - tattlekey/blob - client/tattlekey.c
a11e6c192899b4343ca0b9d16e5a3956d69077c9
[tattlekey] / client / tattlekey.c
1 #include "pico/cyw43_arch.h"
2 #include "pico/stdlib.h"
3 #include "pico/util/queue.h"
4
5 #include "blink.h"
6 #include "button.h"
7 #include "config.h"
8 #include "net.h"
9
10 enum event_type { BUTTONPRESS, SEND };
11 typedef struct {
12 enum event_type type;
13 union {
14 struct {
15 uint32_t timestamp;
16 } buttonpress;
17 struct {
18 uint32_t timestamp;
19 u16_t seq;
20 u8_t send_count;
21 } send;
22 };
23 } event_t;
24
25 queue_t queue;
26
27 uint32_t time_s() { return time_us_64() / 1000000ul; }
28
29 /* Often we don't bother checking for failure (full queue) because
30 * 1. The best thing to do in this unfortunate situation is to blithely
31 * continue, dropping some events; continuing is better than stopping.
32 * 2. Neither interrupt context nor queue-processing context can block
33 * until space is available, or even sit around & blink the LED to
34 * signal a problem.
35 * (We also get a bit of type safety by taking event_t* rather than void*.) */
36 static void queue_try_add_ignoring_errors(queue_t *q, event_t *e) {
37 queue_try_add(q, e);
38 }
39
40 static void button_pressed() {
41 /* This runs in interrupt context; don't linger. */
42 static uint64_t last_button_press_time = 0;
43 uint32_t now = time_s();
44 uint32_t time_since_last_press = now - last_button_press_time;
45 if (time_since_last_press >= config_minimum_seconds_between_button_presses) {
46 last_button_press_time = now;
47 event_t e;
48 e.type = BUTTONPRESS;
49 e.buttonpress.timestamp = now;
50 queue_try_add_ignoring_errors(&queue, &e);
51 }
52 }
53
54 void service_queue() {
55 u16_t seq = 0;
56 while (1) {
57 event_t e;
58 queue_remove_blocking(&queue, &e);
59 switch (e.type) {
60 case BUTTONPRESS: {
61 event_t send_e;
62 send_e.type = SEND;
63 send_e.send.timestamp = e.buttonpress.timestamp;
64 send_e.send.seq = seq++;
65 send_e.send.send_count = 0;
66 queue_try_add_ignoring_errors(&queue, &send_e);
67 } break;
68 case SEND: {
69 uint32_t now = time_s();
70 uint32_t ago = now - e.send.timestamp;
71 send_report(e.send.seq, ago);
72 e.send.send_count++;
73 if (e.send.send_count < config_resend_count)
74 queue_try_add_ignoring_errors(&queue, &e);
75 /* TODO: Sleep elsewhere. */
76 signal(e.send.send_count == 1 ? 2 : 1, 100);
77 sleep_ms(config_resend_interval_ms);
78 } break;
79 default:
80 signal_error_by_blinking();
81 }
82 }
83 }
84
85 int main() {
86 stdio_init_all();
87 if (cyw43_arch_init_with_country(CYW43_COUNTRY_USA))
88 signal_error_by_blinking();
89 cyw43_arch_enable_sta_mode();
90 signal(3, 100);
91 if (cyw43_arch_wifi_connect_timeout_ms(config_wifi_ssid, config_wifi_pass,
92 CYW43_AUTH_WPA2_AES_PSK, 90000))
93 signal_error_by_blinking();
94 signal(2, 300);
95
96 queue_init(&queue, sizeof(event_t), 99);
97
98 begin_listening_for_button_press(button_pressed);
99
100 service_queue();
101 }