]> git.scottworley.com Git - tattlekey/blame_incremental - server/src/main.rs
server: SystemTime → u64 of seconds since UNIX_EPOCH
[tattlekey] / server / src / main.rs
... / ...
CommitLineData
1// tattlekey: A one-key UDP keyboard
2// Copyright (C) 2023 Scott Worley <scottworley@scottworley.com>
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17use serde::Serialize;
18use std::collections::HashMap;
19use std::net::UdpSocket;
20use std::time::{Duration, SystemTime, UNIX_EPOCH};
21
22const MESSAGE_SIZE: usize = 12;
23const LOGFILENAME: &str = "log.csv";
24
25#[derive(Eq, Debug, Hash, PartialEq, Serialize)]
26struct MessageKey {
27 epoch: u32,
28 device: u16,
29 seq: u16,
30}
31
32#[derive(Debug)]
33struct Message {
34 key: MessageKey,
35 t: u64,
36}
37
38impl From<&[u8; MESSAGE_SIZE]> for Message {
39 fn from(value: &[u8; MESSAGE_SIZE]) -> Self {
40 let ago = u32::from_be_bytes(value[8..=11].try_into().expect("I can't count"));
41 let press_time = SystemTime::now() - Duration::new(ago.into(), 0);
42 Self {
43 key: MessageKey {
44 epoch: u32::from_be_bytes(value[0..=3].try_into().expect("I can't count")),
45 device: u16::from_be_bytes(value[4..=5].try_into().expect("I can't count")),
46 seq: u16::from_be_bytes(value[6..=7].try_into().expect("I can't count")),
47 },
48 t: press_time
49 .duration_since(UNIX_EPOCH)
50 .expect("Bad time?")
51 .as_secs(),
52 }
53 }
54}
55impl TryFrom<&[u8]> for Message {
56 type Error = std::array::TryFromSliceError;
57 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
58 match <[u8; MESSAGE_SIZE]>::try_from(value) {
59 Ok(correct_size) => Ok(Message::from(&correct_size)),
60 Err(e) => Err(e),
61 }
62 }
63}
64
65#[derive(Debug)]
66struct Range {
67 start: u64,
68 end: u64,
69}
70impl Range {
71 fn new(t: &u64) -> Self {
72 Self { start: *t, end: *t }
73 }
74 fn contains(&self, t: &u64) -> bool {
75 t > &self.start && t < &self.end
76 }
77 fn extend(&mut self, t: &u64) {
78 if t < &self.start {
79 self.start = *t;
80 }
81 if t > &self.end {
82 self.end = *t;
83 }
84 }
85}
86
87fn merge_message(presses: &mut HashMap<MessageKey, Range>, message: Message) {
88 if let Some(r) = presses.get_mut(&message.key) {
89 if !r.contains(&message.t) {
90 r.extend(&message.t);
91 }
92 } else {
93 presses.insert(message.key, Range::new(&message.t));
94 }
95}
96
97fn open_log_for_writing() -> csv::Writer<std::fs::File> {
98 let log_file_exists = std::path::Path::new(LOGFILENAME).exists();
99 let logfile = std::fs::OpenOptions::new()
100 .create_new(!log_file_exists)
101 .append(true)
102 .open(LOGFILENAME)
103 .expect("Coudln't open log file");
104 csv::WriterBuilder::new()
105 .has_headers(!log_file_exists)
106 .from_writer(logfile)
107}
108
109fn main() {
110 let socket = UdpSocket::bind("0.0.0.0:29803").expect("couldn't bind to address");
111 let mut presses = HashMap::<MessageKey, Range>::new();
112 let mut log = open_log_for_writing();
113 loop {
114 let mut buf = [0; MESSAGE_SIZE];
115 match socket.recv_from(&mut buf) {
116 Err(e) => eprintln!("Didn't receive data: {e}"),
117 Ok((number_of_bytes, src_addr)) => {
118 let filled_buf = &buf[..number_of_bytes];
119 if number_of_bytes != MESSAGE_SIZE {
120 eprintln!("Ignoring short message ({number_of_bytes}) from {src_addr}");
121 continue;
122 }
123 let message = Message::try_from(filled_buf).expect("I can't count");
124 log.serialize((&message.key, message.t))
125 .expect("Couldn't write log");
126 log.flush().expect("Couldn't flush log");
127 merge_message(&mut presses, message);
128 }
129 }
130 }
131}