Skip to content

Commit

Permalink
Fix warnings in rust and wire game data
Browse files Browse the repository at this point in the history
  • Loading branch information
Redrield committed Dec 22, 2019
1 parent 07e4517 commit c2e620e
Show file tree
Hide file tree
Showing 14 changed files with 352 additions and 86 deletions.
296 changes: 280 additions & 16 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ lazy_static = "1.4.0"
rust-embed = "5.1.0"
serde = { version = "1.0.101", features = ["derive"] }
serde_json = "1.0.41"
ds = "0.3.4"
ds = { path = "../ds-rs" }
chrono = "0.4.9"
gilrs = "0.7.2"
spin = "0.5.2"
Expand All @@ -21,3 +21,4 @@ actix-web = "1.0.8"
actix-rt = "0.2.5"
mime_guess = "2.0.1"
futures = "0.1.29"
env_logger = "0.7.1"
14 changes: 3 additions & 11 deletions src/input.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
use gilrs::{Gilrs, Button, Axis, Gamepad};
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, Mutex, RwLock};
use crate::state::State;
use crate::util::map;
use gilrs::{Gilrs, Gamepad};
use std::sync::RwLock;
use lazy_static::lazy_static;
use std::thread;
use ds::JoystickValue;
use gilrs::ev::AxisOrBtn;
use gilrs::ev::state::GamepadState;
use spin::Once;
use std::collections::HashMap;
use std::time::Duration;
use web_view::Handle;
use crate::ipc::Message;

mod mapping;
Expand Down Expand Up @@ -122,8 +116,6 @@ pub fn joystick_callback() -> Vec<Vec<JoystickValue>> {
let mut sorted_joysticks = gil.gamepads().map(|(_, gp)| gp).collect::<Vec<Gamepad>>();
sorted_joysticks.sort_by(|a, b| mappings.get(a.name()).unwrap_or(&0).cmp(mappings.get(b.name()).unwrap_or(&1)));

let mapped_numbers = mappings.values().collect::<Vec<&usize>>();

mapping::apply_mappings(min, mapped_numbers, sorted_joysticks)
mapping::apply_mappings(min, sorted_joysticks)
}

2 changes: 1 addition & 1 deletion src/input/mapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use ds::JoystickValue;
use gilrs::ev::AxisOrBtn;
use crate::util::map;

pub fn apply_mappings(offset: usize, mappings: Vec<&usize>, gamepads: Vec<Gamepad>) -> Vec<Vec<JoystickValue>> {
pub fn apply_mappings(offset: usize, gamepads: Vec<Gamepad>) -> Vec<Vec<JoystickValue>> {
let mut all_values = vec![vec![]; 6];

for (n, gamepad) in gamepads.iter().enumerate() {
Expand Down
11 changes: 3 additions & 8 deletions src/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ use ds::Mode as DsMode;
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
pub enum Message {
UpdateGSM {
gsm: String
},
UpdateTeamNumber {
team_number: u32,
},
Expand Down Expand Up @@ -65,14 +68,6 @@ pub enum Mode {
}

impl Mode {
pub fn from_ds(mode: DsMode) -> Mode {
match mode {
DsMode::Autonomous => Mode::Autonomous,
DsMode::Teleoperated => Mode::Teleoperated,
DsMode::Test => Mode::Test
}
}

pub fn to_ds(self) -> DsMode {
match self {
Mode::Autonomous => DsMode::Autonomous,
Expand Down
27 changes: 15 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
#![feature(decl_macro, proc_macro_hygiene)]
use web_view::{Content, WVResult, Handle};
use resources::Resources;
use ds::{DriverStation, Alliance, TcpPacket};
use ipc::*;
use std::sync::{Arc, Mutex, RwLock};
use std::sync::{Arc, RwLock};
use std::thread;
use std::time::Duration;
use chrono::Local;
use crate::state::State;
use std::path::Path;
use crate::input::MappingUpdate;
use futures::future::Future;

mod resources;
mod ws;
Expand All @@ -26,11 +21,13 @@ static WV_HANDLE: Once<Handle<()>> = Once::new();
static STDOUT_HANDLE: Once<Handle<()>> = Once::new();

fn main() -> WVResult {
env_logger::init();
let port = ws::launch_webserver();
println!("Webserver launched on port {}", port);

let log_file_path = format!("stdout-{}.log", Local::now());
let mut state = Arc::new(RwLock::new(State::new(log_file_path)));
input::input_thread();

let state = Arc::new(RwLock::new(State::new()));

let wv_state = state.clone();
let mut webview = web_view::builder()
Expand All @@ -40,12 +37,18 @@ fn main() -> WVResult {
//.resizable(false)
.debug(true)
.user_data(())
.invoke_handler(move |wv, arg| {
.invoke_handler(move |_wv, arg| {
let mut state = wv_state.write().unwrap();
match serde_json::from_str::<Message>(arg).unwrap() {
Message::UpdateTeamNumber { team_number } => {
println!("Update to {}", team_number);
state.update_ds(team_number);
if team_number != state.ds.team_number() {
state.update_ds(team_number);
}
}
Message::UpdateGSM { gsm } => {
if gsm.len() == 3 {
let _ = state.ds.set_game_specific_message(&gsm);
}
}
Message::UpdateMode { mode } => {
println!("Update mode to {:?}", mode);
Expand Down Expand Up @@ -102,6 +105,7 @@ fn main() -> WVResult {
let stdout_handle = stdout_wv.handle();
STDOUT_HANDLE.call_once(move || stdout_handle);


let ticker_state = state.clone();
let handle = webview.handle();
thread::spawn(move || {
Expand All @@ -123,7 +127,6 @@ fn main() -> WVResult {
}
});

input::input_thread();

loop {
match webview.step() {
Expand Down
52 changes: 21 additions & 31 deletions src/state.rs
Original file line number Diff line number Diff line change
@@ -1,51 +1,41 @@
use ds::{DriverStation, Mode, Alliance, TcpPacket};
use web_view::{Handle, Error, Content, WebView};
use crate::ipc::Message;
use std::thread;
use std::sync::mpsc;
use std::path::Path;
use std::fs::{self, File, OpenOptions};
use std::io::Write;

pub struct State {
pub ds: DriverStation,
mode: Mode,
pub has_joysticks: bool,
log_file: String
}

impl State {
pub fn new(log_file: String) -> State {
// if !Path::new(&log_file).exists() {
// File::create(log_file.clone()).unwrap();
// }
State {
ds: DriverStation::new_team(0, Alliance::new_red(1)),
mode: Mode::Autonomous,
has_joysticks: false,
log_file,
}
}
pub fn new() -> State {
let mut ds = DriverStation::new_team(0, Alliance::new_red(1));

fn update_consumer(&mut self) {
// let mut log_file = OpenOptions::new().write(true).open(&self.log_file).unwrap();
self.ds.set_tcp_consumer(move |packet| {
ds.set_tcp_consumer(move |packet| {
let handle = crate::WV_HANDLE.wait().unwrap();
let stdout_handle = crate::STDOUT_HANDLE.wait().unwrap();
let TcpPacket::Stdout(msg) = packet;
// log_file.write_all(format!("[{:.4}] {}\n", msg.timestamp, msg.message).as_bytes()).unwrap();
let msg = serde_json::to_string(&Message::NewStdout { message: msg.message }).unwrap();
let msg2 = msg.clone();
let _ = handle.dispatch(move |wv| wv.eval(&format!("update({})", msg)));
let _ = stdout_handle.dispatch(move |wv| wv.eval(&format!("update({})", msg2)));
match packet {
TcpPacket::Stdout(msg) => {
let msg = serde_json::to_string(&Message::NewStdout { message: msg.message }).unwrap();
let msg2 = msg.clone();
let _ = handle.dispatch(move |wv| wv.eval(&format!("update({})", msg)));
let _ = stdout_handle.dispatch(move |wv| wv.eval(&format!("update({})", msg2)));
}
TcpPacket::Dummy => {}
}
});

ds.set_joystick_supplier(crate::input::joystick_callback);

State {
ds,
mode: Mode::Autonomous,
has_joysticks: false,
}
}

pub fn update_ds(&mut self, team_number: u32) {
self.ds = DriverStation::new_team(team_number, Alliance::new_red(1));
self.update_consumer();
self.ds.set_mode(self.mode);
self.ds.set_joystick_supplier(crate::input::joystick_callback);
self.ds.set_team_number(team_number);
}

pub fn set_mode(&mut self, mode: Mode) {
Expand Down
3 changes: 0 additions & 3 deletions src/ws.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use std::thread;
use std::path::PathBuf;
use crate::resources;
use std::sync::mpsc;
use actix_web::{HttpServer, web, HttpRequest, Responder, HttpResponse, App};
use actix_web::body::Body;
use resources::Resources;
use std::borrow::Cow;
use actix_web::dev::Server;

fn assets(path: web::Path<String>) -> impl Responder {
let path = path.into_inner();
Expand Down Expand Up @@ -48,7 +46,6 @@ pub fn launch_webserver() -> u16 {
let (port_tx, port_rx) = mpsc::channel();

thread::spawn(move || {
let sys = actix_rt::System::new("http-server");
let server = HttpServer::new(|| {
App::new().route("/", web::get().to(index))
.route("/stdout", web::get().to(stdout))
Expand Down
Binary file added test
Binary file not shown.
7 changes: 7 additions & 0 deletions test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use std::net::UdpSocket;

fn main() {
let sock = UdpSocket::bind("0.0.0.0:1150").unwrap();
println!("Connected! {}", sock.local_addr().unwrap());
loop {}
}
6 changes: 6 additions & 0 deletions ui/src/Lib/Ipc.elm
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ type Request

type IpcMsg
= UpdateTeamNumber { team_number : Int }
| UpdateGSM { gsm : String }
| UpdateMode { mode : Mode }
| UpdateEnableStatus { enabled : Bool }
| JoystickUpdate { removed : Bool, name : String }
Expand Down Expand Up @@ -135,6 +136,11 @@ encodeRequest req =
encodeMsg : IpcMsg -> E.Value
encodeMsg msg =
case msg of
UpdateGSM { gsm } ->
object
[ ("type", E.string "UpdateGSM")
, ("gsm", E.string gsm)
]
UpdateTeamNumber { team_number } ->
object
[ ( "type", E.string "UpdateTeamNumber" )
Expand Down
3 changes: 3 additions & 0 deletions ui/src/Lib/Model.elm
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import Lib.Ipc as Ipc exposing (AllianceStation, Mode, Request, RobotState, robo

type alias Model =
{ teamNumber : String -- Current contents of the team number text field, 0 if empty
, gsm : String -- Current contents of the game data field
, enabled : Bool -- Whether the robot is enabled
, mode : Mode -- The currently selected mode
, alliance : AllianceStation -- The currently selected team station
Expand All @@ -33,6 +34,7 @@ type alias Model =
initModel : Model
initModel =
{ teamNumber = ""
, gsm = ""
, enabled = False
, estopped = False
, mode = Ipc.Autonomous
Expand Down Expand Up @@ -73,6 +75,7 @@ type Msg
| AllianceStationChange AllianceStation
| RequestClick Request
| TeamNumberChange String
| GSMChange String
| BackendMessage Ipc.IpcMsg
| InfiniteListMsg InfiniteList.Model
| ChangePage ActivePage
Expand Down
4 changes: 2 additions & 2 deletions ui/src/Lib/Ui.elm
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ controlTab model =
]
, div [ class "col-2" ]
[ p [ class "lead mt-4" ] [ text <| "Team # " ++ model.teamNumber ]
, p [ class "text-center mt-4", class <| voltageColour model.robotState.voltage ] [ b [] [ text <| Round.round 1 model.robotState.voltage ++ "V" ] ]
, p [ class "text-center mt-4", class <| voltageColour model.robotState.voltage ] [ b [] [ text <| Round.round 2 model.robotState.voltage ++ "V" ] ]
]
, div [ class "col" ]
[ div
Expand Down Expand Up @@ -322,7 +322,7 @@ configTab model =
]
, label [ for "gameDataInput" ] [ text "Game Data" ]
, div [ class "input-group", class "mb-3" ]
[ input [ type_ "text", class "form-control disabled", id "gameDataInput" ] []
[ input [ type_ "text", class "form-control disabled", id "gameDataInput", value model.gsm, onInput GSMChange] []
]
]
, div [ class "col" ] []
Expand Down
10 changes: 9 additions & 1 deletion ui/src/Main.elm
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ updateTeamNumber : Int -> Cmd msg
updateTeamNumber teamNumber =
updateBackend <| Ipc.encodeMsg <| Ipc.UpdateTeamNumber { team_number = teamNumber }

updateGSM : String -> Cmd msg
updateGSM gsm =
updateBackend <| Ipc.encodeMsg <| Ipc.UpdateGSM { gsm = gsm }

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
Expand Down Expand Up @@ -127,7 +130,7 @@ update msg model =
( model, Cmd.none )

Config ->
( model, updateTeamNumber <| (model.teamNumber |> String.toInt |> Maybe.withDefault 0) )
( model, Cmd.batch [ updateTeamNumber <| (model.teamNumber |> String.toInt |> Maybe.withDefault 0), updateGSM <| model.gsm ] )

JoysticksPage ->
( model, Cmd.none )
Expand Down Expand Up @@ -168,6 +171,11 @@ update msg model =
in
( { model | joystickMappings = updatedJoysticks }, updateBackend <| Ipc.encodeMsg <| Ipc.UpdateJoystickMapping { name = name, pos = n } )

GSMChange gsm ->
if String.length gsm <= 3 then
({model | gsm = gsm }, Cmd.none)
else (model, Cmd.none)

TeamNumberChange team ->
if String.length team <= 4 then
case String.toInt team of
Expand Down

0 comments on commit c2e620e

Please sign in to comment.