1 // tattlekey: A one-key UDP keyboard
2 // Copyright (C) 2023 Scott Worley <scottworley@scottworley.com>
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.
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.
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/>.
18 use std::collections::HashMap;
19 use std::net::UdpSocket;
20 use std::time::{Duration, SystemTime, UNIX_EPOCH};
22 const MESSAGE_SIZE: usize = 12;
23 const LOGFILENAME: &str = "log.csv";
25 #[derive(Eq, Debug, Hash, PartialEq)]
32 #[derive(Debug, Serialize)]
40 fn key(&self) -> MessageKey {
49 impl From<&[u8; MESSAGE_SIZE]> for Message {
50 fn from(value: &[u8; MESSAGE_SIZE]) -> Self {
51 let ago = u32::from_be_bytes(value[8..=11].try_into().expect("I can't count"));
52 let press_time = SystemTime::now() - Duration::new(ago.into(), 0);
54 epoch: u32::from_be_bytes(value[0..=3].try_into().expect("I can't count")),
55 device: u16::from_be_bytes(value[4..=5].try_into().expect("I can't count")),
56 seq: u16::from_be_bytes(value[6..=7].try_into().expect("I can't count")),
58 .duration_since(UNIX_EPOCH)
64 impl TryFrom<&[u8]> for Message {
65 type Error = std::array::TryFromSliceError;
66 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
67 match <[u8; MESSAGE_SIZE]>::try_from(value) {
68 Ok(correct_size) => Ok(Message::from(&correct_size)),
80 fn new(t: &u64) -> Self {
81 Self { start: *t, end: *t }
83 fn contains(&self, t: &u64) -> bool {
84 t > &self.start && t < &self.end
86 fn extend(&mut self, t: &u64) {
96 fn merge_message(presses: &mut HashMap<MessageKey, Range>, message: Message) {
97 let key = message.key();
98 if let Some(r) = presses.get_mut(&key) {
99 if !r.contains(&message.t) {
100 r.extend(&message.t);
103 presses.insert(key, Range::new(&message.t));
107 fn open_log_for_writing() -> csv::Writer<std::fs::File> {
108 let log_file_exists = std::path::Path::new(LOGFILENAME).exists();
109 let logfile = std::fs::OpenOptions::new()
110 .create_new(!log_file_exists)
113 .expect("Coudln't open log file");
114 csv::WriterBuilder::new()
115 .has_headers(!log_file_exists)
116 .from_writer(logfile)
120 let socket = UdpSocket::bind("0.0.0.0:29803").expect("couldn't bind to address");
121 let mut presses = HashMap::<MessageKey, Range>::new();
122 let mut log = open_log_for_writing();
124 let mut buf = [0; MESSAGE_SIZE];
125 match socket.recv_from(&mut buf) {
126 Err(e) => eprintln!("Didn't receive data: {e}"),
127 Ok((number_of_bytes, src_addr)) => {
128 let filled_buf = &buf[..number_of_bytes];
129 if number_of_bytes != MESSAGE_SIZE {
130 eprintln!("Ignoring short message ({number_of_bytes}) from {src_addr}");
133 let message = Message::try_from(filled_buf).expect("I can't count");
134 log.serialize(&message).expect("Couldn't write log");
135 log.flush().expect("Couldn't flush log");
136 merge_message(&mut presses, message);