PixSpace/src/tracker.rs

107 lines
3.3 KiB
Rust

use bevy::prelude::*;
extern crate bytes;
extern crate vrpn;
extern crate crossbeam;
// use futures_lite::future;
use rand::Rng;
use std::time::{Duration, Instant};
use bytes::{Bytes, BytesMut};
use std::{
io::{self, Read},
net::{SocketAddr, TcpStream},
};
use std::sync::mpsc::{channel, Receiver};
use vrpn::{
codec::peek_u32,
constants::MAGIC_DATA,
cookie::check_ver_nonfile_compatible,
handler::{HandlerCode, TypedHandler},
message::MessageSize,
sync_io::{read_cookie, write_cookie, EndpointSyncTcp},
tracker::PoseReport,
unbuffer, CookieData, Message, Result, SequencedGenericMessage, TypeDispatcher,
TypedBodylessHandler, Unbuffer,
};
#[derive(Resource, Debug)]
pub struct Tracker;
impl FromWorld for Tracker {
fn from_world(world: &mut World) -> Self {
info!("Test here!");
std::thread::spawn(move || {
// 212.201.64.122 | 127.0.0.1
let addr: SocketAddr = "212.201.64.122:3883".parse().unwrap();
let mut stream = TcpStream::connect(addr).unwrap();
stream.set_nodelay(true).unwrap();
// We first write our cookie, then read and check the server's cookie, before the loop.
write_cookie(&mut stream, CookieData::from(MAGIC_DATA)).unwrap();
let cookie_buf = read_cookie(&mut stream).unwrap();
let mut cookie_buf = Bytes::from(&cookie_buf[..]);
CookieData::unbuffer_ref(&mut cookie_buf)
.and_then(|msg| check_ver_nonfile_compatible(msg.version))
.unwrap();
// Not actually doing anything with the messages here, just receiving them and printing them.
loop {
let mut buf = BytesMut::new();
// Read the message header and padding
buf.resize(24, 0);
stream.read_exact(buf.as_mut()).unwrap();
// Peek the size field, to compute the MessageSize.
let total_len = peek_u32(&buf.clone().freeze()).unwrap().unwrap();
let size = MessageSize::from_length_field(total_len);
// Read the body of the message
let mut body_buf = BytesMut::new();
body_buf.resize(size.padded_body_size(), 0);
stream.read_exact(body_buf.as_mut()).unwrap();
// Combine the body with the header
buf.extend_from_slice(&body_buf[..]);
let mut buf = buf.freeze();
// Unbuffer the message.
let unbuffered = SequencedGenericMessage::unbuffer_ref(&mut buf).unwrap();
let message = Message::from(unbuffered);
// let result: Message<PoseReport> = Message::try_from_generic(&message)?;
let result = Message::<PoseReport>::try_from_generic(&message);
match result {
Ok(result) => {
eprintln!("Pose from tracker {:?}",result.body);
// sender_th.send(result.body).unwrap();
},
Err(_) => { /* silently fail */ }
}
}
});
Self {
// rx = receiver.clone()
}
}
}