initial commit

This commit is contained in:
Данила Горнушко 2024-05-27 17:19:21 +03:00
commit f4d82224a3
8 changed files with 907 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

6
.idea/.gitignore generated vendored Normal file
View file

@ -0,0 +1,6 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
/out/

11
.idea/hailsens_logger.iml generated Normal file
View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="EMPTY_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
.idea/modules.xml generated Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/hailsens_logger.iml" filepath="$PROJECT_DIR$/.idea/hailsens_logger.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

513
Cargo.lock generated Normal file
View file

@ -0,0 +1,513 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "0.6.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b"
[[package]]
name = "anstyle-parse"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a64c907d4e79225ac72e2a354c9ce84d50ebb4586dee56c82b3ee73004f537f5"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19"
dependencies = [
"anstyle",
"windows-sys",
]
[[package]]
name = "anyhow"
version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cfg_aliases"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"
[[package]]
name = "clap"
version = "4.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce"
[[package]]
name = "colorchoice"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422"
[[package]]
name = "core-foundation-sys"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]]
name = "crc"
version = "3.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69e6e4d7b33a94f0991c26729976b10ebde1d34c3ee82408fb536164fa10d636"
dependencies = [
"crc-catalog",
]
[[package]]
name = "crc-catalog"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
[[package]]
name = "ctrlc"
version = "3.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "672465ae37dc1bc6380a6547a8883d5dd397b0f1faaad4f265726cc7042a5345"
dependencies = [
"nix 0.28.0",
"windows-sys",
]
[[package]]
name = "env_filter"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a009aa4810eb158359dda09d0c87378e4bbb89b5a801f016885a4707ba24f7ea"
dependencies = [
"log",
"regex",
]
[[package]]
name = "env_logger"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38b35839ba51819680ba087cd351788c9a3c476841207e0b8cee0b04722343b9"
dependencies = [
"anstream",
"anstyle",
"env_filter",
"humantime",
"log",
]
[[package]]
name = "hailsens_logger"
version = "0.1.0"
dependencies = [
"anyhow",
"clap",
"crc",
"ctrlc",
"env_logger",
"hound",
"log",
"serialport",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hound"
version = "3.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62adaabb884c94955b19907d60019f4e145d091c75345379e70d1ee696f7854f"
[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]
name = "io-kit-sys"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "617ee6cf8e3f66f3b4ea67a4058564628cde41901316e19f559e14c7c72c5e7b"
dependencies = [
"core-foundation-sys",
"mach2",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800"
[[package]]
name = "libc"
version = "0.2.155"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
[[package]]
name = "log"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
[[package]]
name = "mach2"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b955cdeb2a02b9117f121ce63aa52d08ade45de53e48fe6a38b39c10f6f709"
dependencies = [
"libc",
]
[[package]]
name = "memchr"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
[[package]]
name = "nix"
version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b"
dependencies = [
"bitflags 1.3.2",
"cfg-if",
"libc",
]
[[package]]
name = "nix"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4"
dependencies = [
"bitflags 2.5.0",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "proc-macro2"
version = "1.0.83"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b33eb56c327dec362a9e55b3ad14f9d2f0904fb5a5b03b513ab5465399e9f43"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serialport"
version = "4.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f5a15d0be940df84846264b09b51b10b931fb2f275becb80934e3568a016828"
dependencies = [
"bitflags 2.5.0",
"cfg-if",
"core-foundation-sys",
"io-kit-sys",
"mach2",
"nix 0.26.4",
"regex",
"scopeguard",
"unescaper",
"winapi",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cdcff5"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.61"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unescaper"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0adf6ad32eb5b3cadff915f7b770faaac8f7ff0476633aa29eb0d9584d889d34"
dependencies = [
"thiserror",
]
[[package]]
name = "unicode-ident"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "utf8parse"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
[[package]]
name = "windows_i686_gnu"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
[[package]]
name = "windows_i686_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"

14
Cargo.toml Normal file
View file

@ -0,0 +1,14 @@
[package]
name = "hailsens_logger"
version = "0.1.0"
edition = "2021"
[dependencies]
serialport = {version="4.3.0", default-features=false}
log = "0.4.21"
env_logger = "0.11.3"
hound = "3.5.1"
clap = { version = "4.5.4", features = ["derive"] }
ctrlc = "3.2.0"
anyhow = "1.0.86"
crc = "3.2.1"

348
src/main.rs Normal file
View file

@ -0,0 +1,348 @@
use anyhow::{Context, Result};
use clap::Parser;
use crc::{Crc, CRC_16_IBM_3740};
use log::{debug, error, info, LevelFilter};
use serialport::SerialPort;
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
const MAX_DATA_LEN: usize = 1024 * 2 + 4 + 2;
#[derive(Parser, Debug)]
#[command(name = "Hailsens Logger", version, about, long_about = None)]
struct Args {
#[arg(short, long, required = true)]
port: String,
#[arg(short = 'i', long = "id", default_value_t = 5)]
device_id: u32,
#[arg(short, long, default_value_t = 115_200)]
baud_rate: u32,
/// Turn debugging information on
#[arg(short, long, action = clap::ArgAction::Count)]
debug: u8,
}
fn main() {
// Initialize logging with debug level
env_logger::builder()
.filter_level(LevelFilter::Info)
.format_timestamp_millis()
.init();
let args = Args::parse();
debug!("Trying to open the serial port: {}", args.port);
let mut port = match serialport::new(args.port, args.baud_rate).open() {
Ok(p) => {
debug!("Successfully opened the serial port");
p
}
Err(e) => {
error!("Failed to open serial port: {}", e);
return;
}
};
port.set_timeout(calculate_timeout(args.baud_rate, 30))
.unwrap();
let command = format!("@{} name\n", args.device_id);
let response = process_command(&mut port, command).unwrap();
debug!("We got some response: {}", response);
if response.contains("'HAILSENS'") {
info!("Detected hailsens.")
} else {
panic!("Couldn't detect hailsens!")
}
get_threshold(&mut port, args.device_id).expect("Couldn't get threshold");
let winsize = get_winsize(&mut port, args.device_id).expect("Couldn't get winsize") as usize;
debug!("Expected buf size is: {}", exp_buf_size(winsize));
let spec = hound::WavSpec {
channels: 1,
sample_rate: get_sample_rate(&mut port, args.device_id),
bits_per_sample: 16,
sample_format: hound::SampleFormat::Int,
};
info!("Starting main loop...");
let running = Arc::new(AtomicBool::new(true));
let r = running.clone();
// Set up Ctrl-C handler
ctrlc::set_handler(move || {
info!("Ctrl-C pressed! Initiating shutdown...");
r.store(false, Ordering::SeqCst);
})
.unwrap();
info!("Press Ctrl-C to stop");
let mut last_chunk_id: u32 = 0;
let mut err_counter: u32 = 0;
while running.load(Ordering::SeqCst) {
// getting stats
let cur_chunk_id = match get_stats(&mut port, args.device_id) {
Err(e) => {
error!("Couldn't read adcstats: {}", e);
err_counter += 1;
if err_counter > 10 {
panic!("Too many error! Exiting...")
}
error!("Trying again in 500ms");
std::thread::sleep(Duration::from_millis(500));
continue;
}
Ok(value) => {
err_counter = err_counter.saturating_sub(1);
value
}
};
if cur_chunk_id != last_chunk_id {
info!("New data available: {}", cur_chunk_id);
last_chunk_id = cur_chunk_id;
info!("Getting new chunk!");
match get_chunk(&mut port, args.device_id, args.baud_rate, winsize) {
Some(data) => {
info!("Received new data with len: {}", data.len());
}
_ => {
error!("Couldn't receive new data!");
}
}
}
std::thread::sleep(Duration::from_millis(100));
}
}
fn get_stats(port: &mut Box<dyn SerialPort>, id: u32) -> Result<u32> {
let command = format!("@{} adcstats\n", id);
let response = process_command(port, command).unwrap();
let mut split = response.split_whitespace();
let num_since_startup: u32 = split.next().context("Missing value")?.parse()?;
let _num_since_last_read: u32 = split.next().context("Missing value")?.parse()?;
let _num_in_10min: u32 = split.next().context("Missing value")?.parse()?;
debug!("Got num_since_startup: {}", num_since_startup);
Ok(num_since_startup)
}
fn get_winsize(port: &mut Box<dyn SerialPort>, id: u32) -> Option<u32> {
debug!("Getting window size...");
let command = format!("@{} winsize\n", id);
let response = process_command(port, command).unwrap();
let winsize_str = response.split_whitespace().nth(3);
match winsize_str {
Some(num_str) => {
if let Ok(number) = num_str.parse::<u32>() {
info!("The current window size is: {}", number);
Some(number)
} else {
None
}
}
None => None,
}
}
fn get_threshold(port: &mut Box<dyn SerialPort>, id: u32) -> Option<u32> {
let command = format!("@{} adcthresh\n", id);
let response = process_command(port, command).unwrap();
let number_str = response.split_whitespace().nth(3);
match number_str {
Some(num_str) => {
if let Ok(number) = num_str.parse::<u32>() {
info!("The current Goertzel threshold is: {}", number);
Some(number)
} else {
None
}
}
None => None,
}
}
fn get_sample_rate(port: &mut Box<dyn SerialPort>, id: u32) -> u32 {
let command = format!("@{} srate\n", id);
let response = process_command(port, command).unwrap();
let mut split = response.split_whitespace();
let adc_div: u32 = split
.next()
.expect("Failed to parse adc_div")
.parse()
.expect("Failed to parse adc_div");
let adc_sample_time: i32 = split
.next()
.expect("Failed to parse adc_sample_time")
.parse()
.expect("Failed to parse adc_sample_time");
let sample_times: HashMap<i32, Option<f64>> = [
(-1, None),
(0, Some(1.5)),
(1, Some(3.5)),
(2, Some(7.5)),
(3, Some(12.5)),
(4, Some(19.5)),
(5, Some(39.5)),
(6, Some(79.5)),
(7, Some(160.5)),
]
.iter()
.cloned()
.collect();
let adc_div_dict: HashMap<u32, u32> = [
(0x0, 1),
(0x2000, 2),
(0x2800, 4),
(0x3000, 8),
(0x3800, 16),
]
.iter()
.cloned()
.collect();
let fallback_freq = 200_000;
let mut use_fallback = false;
if !sample_times.contains_key(&adc_sample_time) {
error!("Received invalid ADC sample time!");
use_fallback = true;
} else if sample_times[&adc_sample_time].is_none() {
error!("ADC sample time not supported");
use_fallback = true;
} else if !adc_div_dict.contains_key(&adc_div) {
error!("Received invalid ADC divider");
use_fallback = true;
}
if use_fallback {
info!(
"Using fallback ADC sample rate: {}",
nice_freq_string(fallback_freq)
);
fallback_freq
} else {
let adc_div_val = adc_div_dict[&adc_div];
let adc_sample_time_val = sample_times[&adc_sample_time].unwrap();
let res = ((16_000_000.0 / adc_div_val as f64) / (adc_sample_time_val + 12.5)) as u32;
info!(
"Using calculated ADC sample rate: {}",
nice_freq_string(res)
);
res
}
}
fn process_command(port: &mut Box<dyn SerialPort>, command: String) -> Option<String> {
debug!("Writing command to the serial port: {}", command);
port.write_all(command.as_bytes())
.expect("Failed to write to serial port!");
port.flush().expect("Failed to flush serial port!");
debug!("Waiting for response from the serial port...");
let mut reader = BufReader::new(port);
let mut response = String::new();
match reader.read_line(&mut response) {
Ok(_) => {
debug!("Received response from the serial port");
Some(response)
}
Err(ref e) if e.kind() == std::io::ErrorKind::TimedOut => {
debug!("Read timed out");
None
}
Err(e) => {
panic!("Failed to read from serial port: {}", e);
}
}
}
fn nice_freq_string(freq_hz: u32) -> String {
if freq_hz < 1000 {
format!("{:.2} Hz", freq_hz)
} else if freq_hz < 1_000_000 {
format!("{:.2} kHz", freq_hz / 1000)
} else {
format!("{:.2} MHz", freq_hz / 1_000_000)
}
}
fn calculate_timeout(baud_rate: u32, data_length: usize) -> Duration {
let bits_to_transmit = (data_length * 10) as f64;
let timeout_s = bits_to_transmit / (baud_rate as f64);
Duration::from_millis((timeout_s * 1000.0 + 10.0) as u64)
}
fn get_chunk(
port: &mut Box<dyn SerialPort>,
id: u32,
baud_rate: u32,
win_size: usize,
) -> Option<Vec<u8>> {
let command = format!("@{} convbuf\n", id);
debug!("Writing convbuf to the serial port");
port.write_all(command.as_bytes())
.expect("Failed to write to serial port!");
port.flush().expect("Failed to flush serial port!");
debug!("Waiting for response from the serial port...");
let mut adc_buffer: Vec<u8> = vec![0; MAX_DATA_LEN];
std::thread::sleep(calculate_timeout(baud_rate, exp_buf_size(win_size)));
match port.read(adc_buffer.as_mut_slice()) {
Ok(len) => {
debug!("Buffer is received with len: {}", len);
}
Err(ref e) if e.kind() == std::io::ErrorKind::TimedOut => {
debug!("Read timed out");
return None;
}
Err(e) => {
panic!("Failed to read from serial port: {}", e);
}
}
debug!("Checking header...");
if header_is_ok(&adc_buffer) {
debug!("Header is ok!");
} else {
error!("Header is corrupted!");
return None;
}
let data_slice = adc_buffer.get(4..4 + win_size * 2);
let crc_slice: Option<[u8; 2]> = adc_buffer.get(4 + win_size * 2..).and_then(|slice| {
if slice.len() >= 2 {
Some([slice[0], slice[1]])
} else {
None
}
});
match (data_slice, crc_slice) {
(Some(data_buf), Some(crc_buf)) => {
let crc16_obj = Crc::<u16>::new(&CRC_16_IBM_3740);
let crc_calculated = crc16_obj.checksum(data_buf);
let received_crc = u16::from_le_bytes(crc_buf);
if received_crc != crc_calculated {
error!(
"CRC mismatch! Received CRC: {:04X}, Calculated CRC: {:04X}",
received_crc, crc_calculated
);
None
} else {
debug!("CRC is correct!");
Some(data_buf.to_vec())
}
}
_ => {
error!("Couldn't slice received data!");
None
}
}
}
fn header_is_ok(vec: &[u8]) -> bool {
vec.get(0..4)
.map(|bytes| u32::from_be_bytes(bytes.try_into().unwrap()))
.unwrap_or_default()
== 0x55AA55AA
}
fn exp_buf_size(win_size: usize) -> usize {
win_size * 2 + 6
}