]> git.scottworley.com Git - tattlekey/blob - server/src/main.rs
c31f873ba08a103cc0e6a2f856b2bb8a3debf44b
[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 std::net::UdpSocket;
18 use std::time::{Duration, SystemTime};
19
20 const MESSAGE_SIZE: usize = 12;
21
22 #[derive(Debug)]
23 struct MessageKey {
24 epoch: u32,
25 device: u16,
26 seq: u16,
27 }
28
29 #[derive(Debug)]
30 struct Message {
31 key: MessageKey,
32 ago: u32,
33 t: SystemTime,
34 }
35
36 impl From<&[u8; MESSAGE_SIZE]> for Message {
37 fn from(value: &[u8; MESSAGE_SIZE]) -> Self {
38 let ago = u32::from_be_bytes(value[8..=11].try_into().expect("I can't count"));
39 Self {
40 key: MessageKey {
41 epoch: u32::from_be_bytes(value[0..=3].try_into().expect("I can't count")),
42 device: u16::from_be_bytes(value[4..=5].try_into().expect("I can't count")),
43 seq: u16::from_be_bytes(value[6..=7].try_into().expect("I can't count")),
44 },
45 ago,
46 t: SystemTime::now() - Duration::new(ago.into(), 0),
47 }
48 }
49 }
50 impl TryFrom<&[u8]> for Message {
51 type Error = std::array::TryFromSliceError;
52 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
53 match <[u8; MESSAGE_SIZE]>::try_from(value) {
54 Ok(correct_size) => Ok(Message::from(&correct_size)),
55 Err(e) => Err(e),
56 }
57 }
58 }
59
60 fn main() {
61 let socket = UdpSocket::bind("0.0.0.0:29803").expect("couldn't bind to address");
62 loop {
63 let mut buf = [0; MESSAGE_SIZE];
64 match socket.recv_from(&mut buf) {
65 Err(e) => eprintln!("Didn't receive data: {e}"),
66 Ok((number_of_bytes, src_addr)) => {
67 let filled_buf = &buf[..number_of_bytes];
68 if number_of_bytes != MESSAGE_SIZE {
69 eprintln!("Ignoring short message ({number_of_bytes}) from {src_addr}");
70 continue;
71 }
72 let message = Message::try_from(filled_buf).expect("I can't count");
73 println!("Got packet from {src_addr}: {message:?}");
74 }
75 }
76 }
77 }