]> git.scottworley.com Git - tattlekey/blob - server/src/main.rs
573edc580a8a99fc1671e37cb9cb90f6df108c88
[tattlekey] / server / src / main.rs
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
17 use serde::Serialize;
18 use std::collections::HashMap;
19 use std::net::UdpSocket;
20 use std::time::{Duration, SystemTime};
21
22 const MESSAGE_SIZE: usize = 12;
23 const LOGFILENAME: &str = "log.csv";
24
25 #[derive(Eq, Debug, Hash, PartialEq, Serialize)]
26 struct MessageKey {
27 epoch: u32,
28 device: u16,
29 seq: u16,
30 }
31
32 #[derive(Debug)]
33 struct Message {
34 key: MessageKey,
35 t: SystemTime,
36 }
37
38 impl 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 Self {
42 key: MessageKey {
43 epoch: u32::from_be_bytes(value[0..=3].try_into().expect("I can't count")),
44 device: u16::from_be_bytes(value[4..=5].try_into().expect("I can't count")),
45 seq: u16::from_be_bytes(value[6..=7].try_into().expect("I can't count")),
46 },
47 t: SystemTime::now() - Duration::new(ago.into(), 0),
48 }
49 }
50 }
51 impl TryFrom<&[u8]> for Message {
52 type Error = std::array::TryFromSliceError;
53 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
54 match <[u8; MESSAGE_SIZE]>::try_from(value) {
55 Ok(correct_size) => Ok(Message::from(&correct_size)),
56 Err(e) => Err(e),
57 }
58 }
59 }
60
61 #[derive(Debug)]
62 struct Range {
63 start: SystemTime,
64 end: SystemTime,
65 }
66 impl Range {
67 fn new(t: &SystemTime) -> Self {
68 Self { start: *t, end: *t }
69 }
70 fn contains(&self, t: &SystemTime) -> bool {
71 t > &self.start && t < &self.end
72 }
73 fn extend(&mut self, t: &SystemTime) {
74 if t < &self.start {
75 self.start = *t;
76 }
77 if t > &self.end {
78 self.end = *t;
79 }
80 }
81 }
82
83 fn main() {
84 let log_file_exists = std::path::Path::new(LOGFILENAME).exists();
85 let logfile = std::fs::OpenOptions::new()
86 .create_new(!log_file_exists)
87 .append(true)
88 .open(LOGFILENAME)
89 .expect("Coudln't open log file");
90 let mut log = csv::WriterBuilder::new()
91 .has_headers(!log_file_exists)
92 .from_writer(logfile);
93 let mut presses = HashMap::<MessageKey, Range>::new();
94 let socket = UdpSocket::bind("0.0.0.0:29803").expect("couldn't bind to address");
95 loop {
96 let mut buf = [0; MESSAGE_SIZE];
97 match socket.recv_from(&mut buf) {
98 Err(e) => eprintln!("Didn't receive data: {e}"),
99 Ok((number_of_bytes, src_addr)) => {
100 let filled_buf = &buf[..number_of_bytes];
101 if number_of_bytes != MESSAGE_SIZE {
102 eprintln!("Ignoring short message ({number_of_bytes}) from {src_addr}");
103 continue;
104 }
105 let message = Message::try_from(filled_buf).expect("I can't count");
106 log.serialize((&message.key, message.t))
107 .expect("Couldn't write log");
108 log.flush().expect("Couldn't flush log");
109 if let Some(r) = presses.get_mut(&message.key) {
110 if !r.contains(&message.t) {
111 r.extend(&message.t);
112 }
113 } else {
114 presses.insert(message.key, Range::new(&message.t));
115 }
116 }
117 }
118 }
119 }