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