Cleaning up

This commit is contained in:
2020-01-29 10:05:55 +01:00
parent 710ae6c729
commit 587196ac5d
17 changed files with 100 additions and 170 deletions

View File

@@ -6,6 +6,9 @@ use serde_json::json;
use std::i64;
use std::io::Write;
use serde_derive::Deserialize;
use std::fs::File;
use std::io::prelude::*;
use std::time::{Duration, Instant};
use tokio::io::AsyncWriteExt;
use tokio::net::udp::SendHalf;
@@ -14,13 +17,19 @@ use tokio_tungstenite::connect_async;
use tungstenite::protocol::Message;
use url::Url;
#[derive(Debug, Deserialize)]
struct Conf {
filemode: bool,
rssi_threshold: i32,
video_sources: Vec<String>,
lap_sources: Vec<String>,
laptime_sources: Vec<String>,
}
async fn rssi_timer(udpchanneltx: futures::channel::mpsc::UnboundedSender<String>) {
loop {
Delay::new(Duration::from_secs(3)).await;
Delay::new(Duration::from_secs(1)).await;
udpchanneltx.unbounded_send("S0r\n".to_string()).unwrap();
}
}
@@ -36,14 +45,13 @@ async fn programm_to_udp(
}
}
async fn udp_comm(appconf: Conf, senddata: futures::channel::mpsc::UnboundedSender<Message>) {
let mut drone_active = false;
async fn udp_comm(appconf: &Conf, senddata: futures::channel::mpsc::UnboundedSender<Message>) {
let mut drone_active = vec![false, false, false, false, false, false]; // There ia a maximum os 6 receivers
// Setup the UDP Socket
let mut now = Instant::now();
let mut udpsocket = UdpSocket::bind("0.0.0.0:0").await.unwrap();
udpsocket
.connect("127.0.0.1:9000") // 192.168.0.141:9000"
.connect("192.168.0.141:9000")
.await
.expect("could not connect to udp ");
@@ -57,83 +65,86 @@ async fn udp_comm(appconf: Conf, senddata: futures::channel::mpsc::UnboundedSend
tokio::spawn(rssi_timer(udpchanneltx.clone()));
loop {
let mut buf: [u8; 20] = [0; 20];
let mut buf: [u8; 500] = [0; 500];
let len = udprx.recv(&mut buf).await.unwrap();
let result = Vec::from(&buf[0..len]);
let display_result = result.clone();
let result_str = String::from_utf8(display_result).unwrap();
println!("received message: {:?}", result_str);
if result_str.contains("S0R1") {
/*
TODO: We should start the racecounter here
let source_id = "LAPTIME";
let request = json!({"request-type":"SetTextFreetype2Properties", "source":source_id,"message-id": random::<f64>().to_string(), "text": now.elapsed().as_millis().to_string() });
let request = json!({"request-type":"SetTextFreetype2Properties", "source":appconf.la,"message-id": random::<f64>().to_string(), "text": now.elapsed().as_millis().to_string() });
now = Instant::now();
senddata
senddata
.unbounded_send(Message::Text(request.to_string()))
.unwrap();
*/
if appconf.filemode {
write_file("Race active".to_string(), "racestate.txt");
write_file("0".to_string(), "rx1.txt");
write_file("0".to_string(), "rx2.txt");
write_file("0".to_string(), "rx3.txt");
}
}
if result_str.contains("S0R0") {
} else if result_str.contains("S0R0") {
if appconf.filemode {
write_file("Race inactive".to_string(), "racestate.txt");
}
}
} else if result_str.contains("S0r") {
//S0r004A\nS1r0044\nS2r0044
let rxes = result_str.split("\n");
let mut index = 0;
for node in rxes {
if node.len() < 7 {
continue;
};
if result_str.contains("S0r") {
let source_id = "CAM";
//S0r004A\nS1r0044\nS2r0
let rssi = i64::from_str_radix(&result_str[11..15], 16).unwrap_or(-1);
println!("Got RSSI: {}", rssi);
if rssi < 100 {
println!("drone not connected");
if drone_active {
// Send filter on
let request = json!({"request-type":"SetSourceFilterVisibility", "sourceName":source_id,"message-id": random::<f64>().to_string(), "filterName":"mask" , "filterEnabled": true });
now = Instant::now();
senddata
.unbounded_send(Message::Text(request.to_string()))
.unwrap();
drone_active = false;
}
} else {
println!("Drone connected!##########################");
if !drone_active {
// Send filter off
let request = json!({"request-type":"SetSourceFilterVisibility", "sourceName":source_id,"message-id": random::<f64>().to_string(), "filterName":"mask" , "filterEnabled": false });
now = Instant::now();
senddata
.unbounded_send(Message::Text(request.to_string()))
.unwrap();
drone_active = true;
let rssi = i32::from_str_radix(&node[3..7], 16).unwrap_or(0);
if rssi < appconf.rssi_threshold {
// Drone is disconnected
if drone_active[index] {
// Send filter on
let request = json!({"request-type":"SetSourceFilterVisibility", "sourceName":appconf.video_sources[index],"message-id": random::<f64>().to_string(), "filterName":"mask" , "filterEnabled": true });
senddata
.unbounded_send(Message::Text(request.to_string()))
.unwrap();
drone_active[index] = false;
}
} else {
// Drone is connected!
if !drone_active[index] {
// Send filter off
let request = json!({"request-type":"SetSourceFilterVisibility", "sourceName":appconf.video_sources[index],"message-id": random::<f64>().to_string(), "filterName":"mask" , "filterEnabled": false });
senddata
.unbounded_send(Message::Text(request.to_string()))
.unwrap();
drone_active[index] = true;
}
}
index = index + 1;
}
}
if result_str.contains("S0L") {
} else if result_str.contains("S0L") {
// zb sS1L0000000DAF
let lap_time = i64::from_str_radix(&result_str[5..13], 16).unwrap_or(-1);
if lap_time != -1 {
if let Ok(lap_time) = i64::from_str_radix(&result_str[5..13], 16) {
let lap_seconds = (lap_time as f64) / (1000 as f64);
if appconf.filemode {
write_file(lap_seconds.to_string(), "rx1_laptime.txt");
}
// TODO: LapTime to OBS!
}
if let Ok(intval) = &result_str[3..5].parse::<i32>() {
if appconf.filemode {
write_file((intval + 1).to_string(), "rx1.txt");
}
let request = json!({"request-type":"SetTextFreetype2Properties", "source":"RX1","message-id": random::<f64>().to_string(), "text": now.elapsed().as_millis().to_string() });
let request = json!({"request-type":"SetTextFreetype2Properties", "source":appconf.lap_sources[0],"message-id": random::<f64>().to_string(), "text": (intval + 1).to_string() });
senddata
.unbounded_send(Message::Text(request.to_string()))
.unwrap();
}
}
if result_str.contains("S1L") {
} else if result_str.contains("S1L") {
if let Ok(lap_time) = i64::from_str_radix(&result_str[5..13], 16) {
let lap_seconds = (lap_time as f64) / (1000 as f64);
if appconf.filemode {
@@ -145,9 +156,12 @@ async fn udp_comm(appconf: Conf, senddata: futures::channel::mpsc::UnboundedSend
if appconf.filemode {
write_file((intval + 1).to_string(), "rx2.txt");
}
let request = json!({"request-type":"SetTextFreetype2Properties", "source":appconf.lap_sources[1],"message-id": random::<f64>().to_string(), "text": (intval + 1).to_string() });
senddata
.unbounded_send(Message::Text(request.to_string()))
.unwrap();
}
}
if result_str.contains("S2L") {
} else if result_str.contains("S2L") {
if let Ok(lap_time) = i64::from_str_radix(&result_str[5..13], 16) {
let lap_seconds = (lap_time as f64) / (1000 as f64);
if appconf.filemode {
@@ -159,7 +173,13 @@ async fn udp_comm(appconf: Conf, senddata: futures::channel::mpsc::UnboundedSend
if appconf.filemode {
write_file((intval + 1).to_string(), "rx3.txt");
}
let request = json!({"request-type":"SetTextFreetype2Properties", "source":appconf.lap_sources[2],"message-id": random::<f64>().to_string(), "text": (intval + 1).to_string() });
senddata
.unbounded_send(Message::Text(request.to_string()))
.unwrap();
}
} else {
println!("Received unknown message from Chorus: {:?}", result_str);
}
}
}
@@ -207,11 +227,18 @@ async fn main() {
let config = matches.value_of("config").unwrap_or("default.conf");
println!("Value for config: {}", config);
let appconf = Conf {
filemode: matches.is_present("filemode"),
other_setting: false,
};
let mut file = File::open("Config.toml").expect("Unable to open the file");
let mut contents = String::new();
file
.read_to_string(&mut contents)
.expect("Unable to read the file");
let appconf: Conf = toml::from_str(contents.as_str()).unwrap();
/*
let appconf = Conf {
filemode: matches.is_present("filemode"),
rssi_threshold: 100,
};
*/
// Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't
// required we could have used an 'if let' to conditionally get the value)
if let Some(input) = matches.value_of("INPUT") {
@@ -263,5 +290,5 @@ async fn main() {
tokio::spawn(programm_to_ws);
println!("Programm initialized!");
udp_comm(appconf, obstx).await;
udp_comm(&appconf, obstx).await;
}

View File

@@ -1,63 +0,0 @@
//! A simple example of hooking up stdin/stdout to a WebSocket stream.
//!
//! This example will connect to a server specified in the argument list and
//! then forward all data read on stdin to the server, printing out all data
//! received on stdout.
//!
//! Note that this is not currently optimized for performance, especially around
//! buffer management. Rather it's intended to show an example of working with a
//! client.
//!
//! You can use this example together with the `server` example.
use std::env;
use futures::{future, pin_mut, StreamExt};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_tungstenite::connect_async;
use tungstenite::protocol::Message;
#[tokio::main]
async fn main() {
let connect_addr = env::args()
.nth(1)
.unwrap_or_else(|| panic!("this program requires at least one argument"));
let url = url::Url::parse(&connect_addr).unwrap();
let (stdin_tx, stdin_rx) = futures::channel::mpsc::unbounded();
tokio::spawn(read_stdin(stdin_tx));
let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
println!("WebSocket handshake has been successfully completed");
let (write, read) = ws_stream.split();
let stdin_to_ws = stdin_rx.map(Ok).forward(write);
let ws_to_stdout = {
read.for_each(|message| {
async {
let data = message.unwrap().into_data();
tokio::io::stdout().write_all(&data).await.unwrap();
}
})
};
pin_mut!(stdin_to_ws, ws_to_stdout);
future::select(stdin_to_ws, ws_to_stdout).await;
}
// Our helper method which will read data from stdin and send it along the
// sender provided.
async fn read_stdin(tx: futures::channel::mpsc::UnboundedSender<Message>) {
let mut stdin = tokio::io::stdin();
loop {
let mut buf = vec![0; 1024];
let n = match stdin.read(&mut buf).await {
Err(_) | Ok(0) => break,
Ok(n) => n,
};
buf.truncate(n);
tx.unbounded_send(Message::binary(buf)).unwrap();
}
}

View File

@@ -1,33 +0,0 @@
use rand::random;
use serde_json::json;
use std::thread;
use std::thread::sleep;
use std::time::{Duration, Instant};
use tungstenite::{connect, Error, Message, Result};
use url::Url;
fn main() {
let now = Instant::now();
let (mut socket, _) =
connect(Url::parse("ws://localhost:4444/").unwrap()).expect("Could not connect");
let source_id = "LAPTIME";
let new_text = "rusty";
let handler = thread::spawn(|| loop {
let request = json!({"request-type":"SetTextFreetype2Properties", "source":source_id,"message-id": random::<f64>().to_string(), "text": now.elapsed().as_millis().to_string() });
socket
.write_message(Message::Text(request.to_string()))
.unwrap();
println!("{}", now.elapsed().as_secs());
sleep(Duration::from_millis(100));
});
/*
loop {
let msg = socket.read_message().unwrap();
let text = msg.into_text().unwrap_or("".to_string());
println!("{}", text);
}
*/
//socket.close(None).unwrap();
}