]>
Commit | Line | Data |
---|---|---|
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::ser::{Serialize, SerializeStruct, Serializer}; | |
18 | use std::collections::HashMap; | |
19 | use std::net::UdpSocket; | |
20 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; | |
21 | ||
22 | const MESSAGE_SIZE: usize = 12; | |
23 | const LOGFILENAME: &str = "log.csv"; | |
24 | ||
25 | #[derive(Eq, Debug, Hash, PartialEq)] | |
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: u64, | |
36 | } | |
37 | impl Serialize for Message { | |
38 | // https://github.com/BurntSushi/rust-csv/issues/155 | |
39 | // https://github.com/BurntSushi/rust-csv/issues/98 | |
40 | // https://github.com/BurntSushi/rust-csv/pull/223 | |
41 | // csv doesn't support #[serde(flatten)], so we implement this directly. :( | |
42 | fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { | |
43 | let mut row = serializer.serialize_struct("Message", 4)?; | |
44 | row.serialize_field("epoch", &self.key.epoch)?; | |
45 | row.serialize_field("device", &self.key.device)?; | |
46 | row.serialize_field("seq", &self.key.seq)?; | |
47 | row.serialize_field("t", &self.t)?; | |
48 | row.end() | |
49 | } | |
50 | } | |
51 | ||
52 | impl From<&[u8; MESSAGE_SIZE]> for Message { | |
53 | fn from(value: &[u8; MESSAGE_SIZE]) -> Self { | |
54 | let ago = u32::from_be_bytes(value[8..=11].try_into().expect("I can't count")); | |
55 | let press_time = SystemTime::now() - Duration::new(ago.into(), 0); | |
56 | Self { | |
57 | key: MessageKey { | |
58 | epoch: u32::from_be_bytes(value[0..=3].try_into().expect("I can't count")), | |
59 | device: u16::from_be_bytes(value[4..=5].try_into().expect("I can't count")), | |
60 | seq: u16::from_be_bytes(value[6..=7].try_into().expect("I can't count")), | |
61 | }, | |
62 | t: press_time | |
63 | .duration_since(UNIX_EPOCH) | |
64 | .expect("Bad time?") | |
65 | .as_secs(), | |
66 | } | |
67 | } | |
68 | } | |
69 | impl TryFrom<&[u8]> for Message { | |
70 | type Error = std::array::TryFromSliceError; | |
71 | fn try_from(value: &[u8]) -> Result<Self, Self::Error> { | |
72 | match <[u8; MESSAGE_SIZE]>::try_from(value) { | |
73 | Ok(correct_size) => Ok(Message::from(&correct_size)), | |
74 | Err(e) => Err(e), | |
75 | } | |
76 | } | |
77 | } | |
78 | ||
79 | #[derive(Debug)] | |
80 | struct Range { | |
81 | start: u64, | |
82 | end: u64, | |
83 | } | |
84 | impl Range { | |
85 | fn new(t: &u64) -> Self { | |
86 | Self { start: *t, end: *t } | |
87 | } | |
88 | fn contains(&self, t: &u64) -> bool { | |
89 | t > &self.start && t < &self.end | |
90 | } | |
91 | fn extend(&mut self, t: &u64) { | |
92 | if t < &self.start { | |
93 | self.start = *t; | |
94 | } | |
95 | if t > &self.end { | |
96 | self.end = *t; | |
97 | } | |
98 | } | |
99 | } | |
100 | ||
101 | fn merge_message(presses: &mut HashMap<MessageKey, Range>, message: Message) { | |
102 | if let Some(r) = presses.get_mut(&message.key) { | |
103 | if !r.contains(&message.t) { | |
104 | r.extend(&message.t); | |
105 | } | |
106 | } else { | |
107 | presses.insert(message.key, Range::new(&message.t)); | |
108 | } | |
109 | } | |
110 | ||
111 | fn open_log_for_writing() -> csv::Writer<std::fs::File> { | |
112 | let log_file_exists = std::path::Path::new(LOGFILENAME).exists(); | |
113 | let logfile = std::fs::OpenOptions::new() | |
114 | .create_new(!log_file_exists) | |
115 | .append(true) | |
116 | .open(LOGFILENAME) | |
117 | .expect("Coudln't open log file"); | |
118 | csv::WriterBuilder::new() | |
119 | .has_headers(!log_file_exists) | |
120 | .from_writer(logfile) | |
121 | } | |
122 | ||
123 | fn main() { | |
124 | let socket = UdpSocket::bind("0.0.0.0:29803").expect("couldn't bind to address"); | |
125 | let mut presses = HashMap::<MessageKey, Range>::new(); | |
126 | let mut log = open_log_for_writing(); | |
127 | loop { | |
128 | let mut buf = [0; MESSAGE_SIZE]; | |
129 | match socket.recv_from(&mut buf) { | |
130 | Err(e) => eprintln!("Didn't receive data: {e}"), | |
131 | Ok((number_of_bytes, src_addr)) => { | |
132 | let filled_buf = &buf[..number_of_bytes]; | |
133 | if number_of_bytes != MESSAGE_SIZE { | |
134 | eprintln!("Ignoring short message ({number_of_bytes}) from {src_addr}"); | |
135 | continue; | |
136 | } | |
137 | let message = Message::try_from(filled_buf).expect("I can't count"); | |
138 | log.serialize(&message).expect("Couldn't write log"); | |
139 | log.flush().expect("Couldn't flush log"); | |
140 | merge_message(&mut presses, message); | |
141 | } | |
142 | } | |
143 | } | |
144 | } |