Cleaning up

This commit is contained in:
Lukas Bachschwell 2020-01-29 10:05:55 +01:00
parent 710ae6c729
commit 587196ac5d
Signed by: lbsadmin
GPG Key ID: CCC6AA87CC8DF425
17 changed files with 100 additions and 170 deletions

13
Cargo.lock generated
View File

@ -113,6 +113,8 @@ dependencies = [
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"pin-project 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)", "pin-project 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)",
"tokio 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "tokio 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
"tokio-tungstenite 0.10.0 (git+https://github.com/snapview/tokio-tungstenite)", "tokio-tungstenite 0.10.0 (git+https://github.com/snapview/tokio-tungstenite)",
@ -694,6 +696,16 @@ name = "serde"
version = "1.0.104" version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "serde_derive"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"proc-macro2 1.0.8 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.45" version = "1.0.45"
@ -1036,6 +1048,7 @@ dependencies = [
"checksum security-framework 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8ef2429d7cefe5fd28bd1d2ed41c944547d4ff84776f5935b456da44593a16df" "checksum security-framework 0.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8ef2429d7cefe5fd28bd1d2ed41c944547d4ff84776f5935b456da44593a16df"
"checksum security-framework-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e31493fc37615debb8c5090a7aeb4a9730bc61e77ab10b9af59f1a202284f895" "checksum security-framework-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e31493fc37615debb8c5090a7aeb4a9730bc61e77ab10b9af59f1a202284f895"
"checksum serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449" "checksum serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "414115f25f818d7dfccec8ee535d76949ae78584fc4f79a6f45a904bf8ab4449"
"checksum serde_derive 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)" = "128f9e303a5a29922045a830221b8f78ec74a5f544944f3d5984f8ec3895ef64"
"checksum serde_json 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)" = "eab8f15f15d6c41a154c1b128a22f2dfabe350ef53c40953d84e36155c91192b" "checksum serde_json 1.0.45 (registry+https://github.com/rust-lang/crates.io-index)" = "eab8f15f15d6c41a154c1b128a22f2dfabe350ef53c40953d84e36155c91192b"
"checksum sha-1 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f7d94d0bede923b3cea61f3f1ff57ff8cdfd77b400fb8f9998949e0cf04163df" "checksum sha-1 0.8.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f7d94d0bede923b3cea61f3f1ff57ff8cdfd77b400fb8f9998949e0cf04163df"
"checksum slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8" "checksum slab 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c111b5bd5695e56cffe5129854aa230b39c93a305372fdbb2668ca2394eea9f8"

View File

@ -12,6 +12,8 @@ toml = "0.5"
futures-timer = "3.0.0" futures-timer = "3.0.0"
clap = "2.33.0" clap = "2.33.0"
url = "2.1.1" url = "2.1.1"
serde = "1.0.97"
serde_derive = "1.0"
serde_json = "1.0" serde_json = "1.0"
rand = "0.7.3" rand = "0.7.3"
tokio = { version = "0.2.11", default-features = false, features = ["io-std", "macros", "udp"] } tokio = { version = "0.2.11", default-features = false, features = ["io-std", "macros", "udp"] }

View File

@ -1,16 +1,7 @@
[LapCountScenes] filemode = false
RX1 = "RX1LAP" rssi_threshold = 100
RX2 = "RX2LAP"
RX3 = "RX3LAP"
RX4 = ""
RX5 = ""
RX6 = ""
[LapTimeScenes] video_sources = [ "RX1", "RX2", "RX3" ]
RX1 = "" lap_sources = [ "RX1Lap", "RX2Lap", "RX3Lap" ]
RX2 = "" laptime_sources = [ "RX1LapTime", "RX2LapTime", "RX3LapTime" ]
RX3 = ""
RX4 = ""
RX5 = ""
RX6 = ""

View File

@ -1 +0,0 @@
Race inactive

View File

@ -1 +0,0 @@
0

View File

@ -1 +0,0 @@
-.-

View File

@ -1 +0,0 @@
0

View File

@ -1 +0,0 @@
-.-

View File

@ -1 +0,0 @@
0

View File

@ -1 +0,0 @@
-.-

View File

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