Skip to content

Commit

Permalink
fix(insim): Missing C codepage, string methods tidy up (#174)
Browse files Browse the repository at this point in the history
* fix: Missing codepage, start to tidy up string methods to make them more idiomatic

* wip

* fix(insim): RaceLaps overflow, fixes #175
  • Loading branch information
theangryangel committed Aug 16, 2024
1 parent c1ab14b commit 77a55ec
Show file tree
Hide file tree
Showing 12 changed files with 457 additions and 238 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ futures-util = { version = "0.3.28" }
if_chain = "1.0.2"
indexmap = "2.1.0"
itertools = { version = "0.13.0" }
once_cell = "1.17.1"
serde = { version = "1.0.188" }
thiserror = "1.0.40"
tokio = { version = "1.11.0" }
Expand Down
15 changes: 15 additions & 0 deletions examples/strobe/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "strobe"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish = false

[dependencies]
clap = { workspace = true, features = ["derive"] }
if_chain = { workspace = true }
insim = { path = "../../insim" }
tokio = { workspace = true, features = ["full"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
3 changes: 3 additions & 0 deletions examples/strobe/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# light-control

Control the lights on your local vehicle. Turn them on and off in a random sequence.
135 changes: 135 additions & 0 deletions examples/strobe/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
//! High level example
//! This example showcases the shortcut methods
use std::{net::SocketAddr, time::Duration};

use clap::Parser;
use insim::{
identifiers::{PlayerId, RequestId},
insim::{IsiFlags, LclFlags, PlayerType, Small, SmallType, Tiny, TinyType},
Packet, Result,
};
use tokio::time::interval;

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
/// host:port of LFS to connect to
addr: SocketAddr,
}

struct ReversibleSequence<T> {
sequence: Vec<T>,
index: usize,
reverse: bool,
}

impl<T: Copy> ReversibleSequence<T> {
fn new(sequence: Vec<T>) -> Self {
ReversibleSequence {
sequence,
index: 0,
reverse: false,
}
}

fn next(&mut self) -> &T {
if self.index >= self.sequence.len() {
self.reverse = !self.reverse;
self.index = 0;
}

let result = if self.reverse {
self.sequence.get(self.sequence.len() - 1 - self.index)
} else {
self.sequence.get(self.index)
};

self.index += 1;
result.unwrap()
}
}

#[tokio::main]
pub async fn main() -> Result<()> {
// Setup tracing_subcriber with some sane defaults
tracing_subscriber::fmt::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();

// Parse our command line arguments, using clap
let cli = Cli::parse();

let mut builder = insim::tcp(cli.addr);

// set our IsiFlags
builder = builder.isi_flags(IsiFlags::LOCAL);

// Establish a connection
let mut connection = builder.connect_async().await?;
tracing::info!("Connected!");

connection
.write(Tiny {
subt: TinyType::Npl,
reqi: RequestId(1),
})
.await?;

let mut plid: Option<PlayerId> = None;

let mut interval = interval(Duration::from_millis(250));

let mut i: usize = 0;

let mut sequence = ReversibleSequence::new(vec![
LclFlags::SIGNAL_LEFT
| LclFlags::LIGHT_OFF
| LclFlags::FOG_REAR_OFF
| LclFlags::FOG_FRONT_OFF,
LclFlags::SIGNAL_OFF | LclFlags::LIGHT_HIGH | LclFlags::FOG_REAR | LclFlags::FOG_FRONT,
LclFlags::SIGNAL_RIGHT
| LclFlags::LIGHT_OFF
| LclFlags::FOG_REAR_OFF
| LclFlags::FOG_FRONT_OFF,
]);

loop {
tokio::select! {

_ = interval.tick() => {
if plid.is_none() {
continue;
}

connection.write(Small { subt: SmallType::Lcl(*sequence.next()), ..Default::default() }).await?;

i = i.wrapping_add(1);
},

packet = connection.read() => {

match packet? {
Packet::Npl(npl) => {

if !npl.ptype.contains(PlayerType::REMOTE) && !npl.ptype.contains(PlayerType::AI) {
plid = Some(npl.plid);
tracing::info!("Woot! local player joined! {:?}", plid);
}
},

Packet::Pll(pll) => {
if plid.map_or(false, |p| p == pll.plid) {
plid = None;

tracing::info!("Local player left!");
}
},

_ => {}

}
},
}
}
}
11 changes: 7 additions & 4 deletions insim/src/insim/mso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::io::SeekFrom;
use bytes::BufMut;
use insim_core::{
binrw::{self, binrw},
string::codepages,
string::{codepages, strip_trailing_nul},
};

use crate::identifiers::{ConnectionId, PlayerId, RequestId};
Expand Down Expand Up @@ -84,12 +84,15 @@ impl binrw::BinRead for Mso {

let msg: Vec<u8> = binrw::helpers::until_eof(reader, endian, ())?;

let name = codepages::to_lossy_string(&name);
let msg = codepages::to_lossy_string(&msg);
let name = codepages::to_lossy_string(strip_trailing_nul(&name));
let msg = codepages::to_lossy_string(strip_trailing_nul(&msg));
(name.len() as u8, format!("{name}{msg}"))
} else {
let msg: Vec<u8> = binrw::helpers::until_eof(reader, endian, ())?;
(0_u8, codepages::to_lossy_string(&msg).to_string())
(
0_u8,
codepages::to_lossy_string(strip_trailing_nul(&msg)).to_string(),
)
};

Ok(Self {
Expand Down
7 changes: 4 additions & 3 deletions insim/src/insim/racelaps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,12 @@ impl BinWrite for RaceLaps {

impl From<u8> for RaceLaps {
fn from(value: u8) -> Self {
let value = value as usize;
match value {
0 => RaceLaps::Practice,
1..=99 => RaceLaps::Laps(value.into()),
100..=190 => RaceLaps::Laps(((value - 100) * 10 + 100).into()),
191..=238 => RaceLaps::Hours((value - 190).into()),
1..=99 => RaceLaps::Laps(value),
100..=190 => RaceLaps::Laps((value - 100) * 10 + 100),
191..=238 => RaceLaps::Hours(value - 190),
_ => RaceLaps::Practice,
}
}
Expand Down
1 change: 0 additions & 1 deletion insim_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,5 @@ bytes = { workspace = true }
encoding_rs = { workspace = true }
if_chain = { workspace = true }
itertools = { workspace = true }
once_cell = { workspace = true }
serde = { workspace = true, features = ["derive"], optional = true }
thiserror = { workspace = true }
Loading

0 comments on commit 77a55ec

Please sign in to comment.