Compare commits

...

2 Commits

Author SHA1 Message Date
yanweitong 0f9f06db53 rebuild log, and add aliyun sms server 2024-01-05 17:47:20 +08:00
yanweitong 972f378389 change to english ocr 2024-01-05 00:39:17 +08:00
13 changed files with 1333 additions and 64 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
.idea .idea
target target
test test
logs

1077
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -10,12 +10,13 @@ edition = "2021"
default = ["pokemmo"] default = ["pokemmo"]
pokemmo = ["screen", "ocr", "joystick", "dep:image", "pokemon", "detector"] pokemmo = ["screen", "ocr", "joystick", "dep:image", "pokemon", "detector","sms"]
screen = ["dep:screenshots"] screen = ["dep:screenshots"]
ocr = ["dep:rusty-tesseract", "dep:image"] ocr = ["dep:rusty-tesseract", "dep:image"]
joystick = ["dep:enigo","dep:rand"] joystick = ["dep:enigo","dep:rand"]
pokemon = [] pokemon = []
detector = ["dep:crossterm"] detector = ["dep:crossterm"]
sms = []
[lib] [lib]
@ -30,4 +31,13 @@ image = { version = "0.24.6", optional = true }
crossterm = { version = "0.27.0", optional = true } crossterm = { version = "0.27.0", optional = true }
rusty-tesseract = { version = "1.1.7", optional = true } rusty-tesseract = { version = "1.1.7", optional = true }
rand = { version = "0.8.5", optional = true } rand = { version = "0.8.5", optional = true }
simple-logging = {version = "2.0.2"}
log4rs = {version = "1.2.0"}
#sms = {version = "0.1.8", optional = true}
futures = "0.3"
reqwest = { version = "0.11.18", features = ["json", "blocking"]}
chrono = { version = "0.4.24"}
ring = "0.16"
urlencoding = "2.1.0"
base64 = "0.21.5"

26
src/base/logger.rs Normal file
View File

@ -0,0 +1,26 @@
pub mod logger {
use log4rs::append::file::FileAppender;
use log4rs::Config;
use log4rs::config::{Appender, Logger, Root};
use log4rs::encode::pattern::PatternEncoder;
use log::LevelFilter;
#[no_mangle]
pub extern "C" fn init_logger(log_file_name: &str, level_filter: LevelFilter) {
let file_path = format!(".\\logs\\{}.log", log_file_name);
let mut config_builder = Config::builder();
let file = FileAppender::builder()
.encoder(Box::new(PatternEncoder::new("[{d(%Y-%m-%d %H:%M:%S%.3f)}] {(\\({tid}\\)):7.7} {({l}):5.5} {m}{n}")))
// .encoder(Box::new(PatternEncoder::new("[{d(%Y-%m-%d %H:%M:%S%.3f)}] {(\\({tid}\\)):7.7} {({l}):5.5} {t} {m}{n}")))
.build(&file_path)
.unwrap();
config_builder = config_builder.appender(Appender::builder().build("file", Box::new(file)));
let mut tag_logger = Logger::builder();
tag_logger = tag_logger.appender("file");
tag_logger = tag_logger.additive(true);
let wecode_log = tag_logger.clone().build("nezha", level_filter);
config_builder = config_builder.logger(wecode_log);
let config = config_builder.build(Root::builder().build(level_filter)).expect("build log failed");
let handle_res = log4rs::init_config(config).expect("init log config failed");
}
}

2
src/base/mod.rs Normal file
View File

@ -0,0 +1,2 @@
pub(crate) mod logger;
pub(crate) mod network;

125
src/base/network.rs Normal file
View File

@ -0,0 +1,125 @@
pub(crate) mod network{
use chrono::{SecondsFormat, Utc};
use std::collections::HashMap;
use ring::hmac;
/// SMS API 版本
const SMS_VERSION: &'static str = "2017-05-25";
/// 签名算法版本。目前为固定值 `1.0`。
const SIGNATURE_VERSION: &'static str = "1.0";
/// 签名方式。目前为固定值 `HMAC-SHA1`。
const SIGNATURE_METHOD: &'static str = "HMAC-SHA1";
/// 指定接口返回数据的格式。可以选择 `JSON` 或者 `XML`。默认为 `XML`。
///
/// 这里选择 `JSON`。
const FORMAT: &'static str = "json";
pub struct Aliyun<'a> {
access_key_id: &'a str,
access_secret: &'a str,
}
impl<'a> Aliyun<'a> {
pub fn new(access_key_id: &'a str, access_secret: &'a str) -> Self {
Self {
access_key_id,
access_secret,
}
}
pub fn send_sms(
&self,
phone_numbers: &'a str,
sign_name: &'a str,
template_code: &'a str,
template_param: &'a str,
) -> Result<HashMap<String, String>, Box<dyn std::error::Error>> {
let mut params = HashMap::new();
params.insert("PhoneNumbers", phone_numbers);
params.insert("SignName", sign_name);
params.insert("TemplateCode", template_code);
params.insert("RegionId", "cn-hangzhou");
params.insert("TemplateParam", template_param);
params.insert("Action", "SendSms");
params.insert("Version", SMS_VERSION);
// 构造规范化请求字符串
let canonicalize_query_string = self.canonicalize_query_string(&params);
// 构造签名字符串
let signature = self.signature(
format!(
"GET&%2F&{}",
urlencoding::encode(&canonicalize_query_string)
)
.as_bytes(),
);
let url = format!(
"https://dysmsapi.aliyuncs.com/?{}&Signature={}",
canonicalize_query_string, signature
);
let client = reqwest::blocking::Client::new();
let resp= client.get(url).send()?.json::<HashMap<String, String>>()?;
// let resp = reqwest::get(url)
// .await?
// .json::<HashMap<String, String>>()
// .await?;
Ok(resp)
}
/// 构造规范化请求字符串
///
/// 详见链接: https://help.aliyun.com/document_detail/315526.html#sectiondiv-y9b-x9s-wvp
fn canonicalize_query_string(&self, params: &HashMap<&str, &'a str>) -> String {
let now = Utc::now();
let signature_nonce = now.timestamp_nanos().to_string();
let timestamp = now.to_rfc3339_opts(SecondsFormat::Secs, true);
let mut all_params = HashMap::new();
all_params.insert("AccessKeyId", self.access_key_id);
all_params.insert("Format", FORMAT);
all_params.insert("SignatureMethod", SIGNATURE_METHOD);
all_params.insert("SignatureNonce", signature_nonce.as_str());
all_params.insert("SignatureVersion", SIGNATURE_VERSION);
all_params.insert("Timestamp", timestamp.as_str());
params.iter().for_each(|(&k, &v)| {
all_params.insert(k, v);
});
let mut vec_arams: Vec<String> = all_params
.iter()
.map(|(&k, &v)| format!("{}={}", k, urlencoding::encode(&v)))
.collect();
vec_arams.sort();
vec_arams.join("&")
}
/// 构建签名字符串
fn signature(&self, string_to_sign: &[u8]) -> String {
let key = hmac::Key::new(
hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
format!("{}&", self.access_secret).as_bytes(),
);
let sign = hmac::sign(&key, string_to_sign);
base64::encode(sign.as_ref())
}
}
}

View File

@ -4,3 +4,5 @@ pub(crate) mod pokemmo;
pub(crate) mod pokemon; pub(crate) mod pokemon;
pub(crate) mod detector; pub(crate) mod detector;
pub(crate) mod ocr; pub(crate) mod ocr;
pub(crate) mod sms;
pub(crate) mod base;

View File

@ -128,7 +128,7 @@ pub mod pokemmo_const_value{
#[derive(Debug)] #[derive(Debug)]
pub enum PokemmoStatus { pub enum PokemmoStatus {
// 遇见闪光 // 遇见闪光
MeetShiny, MeetTarget,
// 无状态 // 无状态
Free, Free,
// 加载遇怪动画 // 加载遇怪动画

View File

@ -15,7 +15,7 @@ pub mod pokemmo {
use crate::joystick::joystick::joystick::{move_once_by_mode, MoveMode, quick_press}; use crate::joystick::joystick::joystick::{move_once_by_mode, MoveMode, quick_press};
use crate::ocr::ocr::ocr::find_string_in_image; use crate::ocr::ocr::ocr::find_string_in_image;
use crate::pokemmo::const_value::pokemmo_const_value::{BUTTON_HL_1, BUTTON_HL_2, BUTTON_HL_3, BUTTON_HL_4, GROUP_5_1, GROUP_5_2, GROUP_5_3, GROUP_5_4, GROUP_5_5, LAST_TEXT_AREA, LOGO, PokemmoStatus, SINGLE_BATTLE, TEMP_BATTLE_TEXT_AREA, TEXT_AREA}; use crate::pokemmo::const_value::pokemmo_const_value::{BUTTON_HL_1, BUTTON_HL_2, BUTTON_HL_3, BUTTON_HL_4, GROUP_5_1, GROUP_5_2, GROUP_5_3, GROUP_5_4, GROUP_5_5, LAST_TEXT_AREA, LOGO, PokemmoStatus, SINGLE_BATTLE, TEMP_BATTLE_TEXT_AREA, TEXT_AREA};
use crate::pokemmo::const_value::pokemmo_const_value::PokemmoStatus::{Free, InBattle, LoadBattle, MeetShiny, Running}; use crate::pokemmo::const_value::pokemmo_const_value::PokemmoStatus::{Free, InBattle, LoadBattle, MeetTarget, Running};
use crate::screen::screen::screen::{Area, screen_shot}; use crate::screen::screen::screen::{Area, screen_shot};
// 单遇闪光 // 单遇闪光
@ -28,7 +28,7 @@ pub mod pokemmo {
loop { loop {
trace!("当前状态:{:?}",status); trace!("当前状态:{:?}",status);
match status { match status {
PokemmoStatus::MeetShiny => { PokemmoStatus::MeetTarget => {
return; return;
} }
PokemmoStatus::Free => { PokemmoStatus::Free => {
@ -37,13 +37,13 @@ pub mod pokemmo {
move_index = move_index + 1; move_index = move_index + 1;
let text = get_last_string(); let text = get_last_string();
trace!("查询战斗文字 : {}",text); trace!("查询战斗文字 : {}",text);
if text.contains("野生") || text.contains("派出") { if text.contains("wild") || text.contains("sent") {
info!("遇怪:{}.",text); info!("遇怪:{}.",text);
meet_pokemmo = text.clone(); meet_pokemmo = text.clone();
status = LoadBattle; status = LoadBattle;
}else { }else {
let temp_battle = read_area(TEMP_BATTLE_TEXT_AREA); let temp_battle = read_area(TEMP_BATTLE_TEXT_AREA);
if temp_battle.contains("战斗") || temp_battle.contains("逃跑"){ if temp_battle.contains("fight") || temp_battle.contains("run"){
status = LoadBattle; status = LoadBattle;
} }
} }
@ -64,20 +64,20 @@ pub mod pokemmo {
PokemmoStatus::InBattle => { PokemmoStatus::InBattle => {
trace!("检查遇怪种类.."); trace!("检查遇怪种类..");
let text = get_text_list(); let text = get_text_list();
let filter_text: Vec<String> = text.into_iter().filter(|x| x.contains("野生")).collect(); let filter_text: Vec<String> = text.into_iter().filter(|x| x.contains("wild")).collect();
if filter_text.is_empty() { if filter_text.is_empty() {
error!("遇怪错误!"); error!("遇怪错误!");
return; return;
} }
let filter_size = filter_text.len(); let filter_size = filter_text.len();
let pokemon_text = filter_text[filter_size - 1].clone(); let pokemon_text = filter_text[filter_size - 1].clone();
if pokemon_text.contains("怪群") { if pokemon_text.contains("horde") {
info!("遇见怪群"); info!("遇见怪群");
let five_names = read_group_5(); let five_names = read_group_5();
for name in five_names { for name in five_names {
for key_word in key_words { for key_word in key_words {
if name.contains(key_word) { if name.contains(key_word) {
status = MeetShiny; status = MeetTarget;
return; return;
} }
} }
@ -88,7 +88,7 @@ pub mod pokemmo {
for key_word in key_words { for key_word in key_words {
if name.contains(key_word) || meet_pokemmo.contains(key_word) { if name.contains(key_word) || meet_pokemmo.contains(key_word) {
info!("遇见{}",key_word); info!("遇见{}",key_word);
status = MeetShiny; status = MeetTarget;
return; return;
} }
} }
@ -117,7 +117,7 @@ pub mod pokemmo {
let mut last_word = get_last_string(); let mut last_word = get_last_string();
// 读取十次后默认成功 // 读取十次后默认成功
let mut times = 0_usize; let mut times = 0_usize;
while !last_word.contains("成功") while !last_word.contains("escaped")
&& !last_word.contains("中逃跑") && !last_word.contains("中逃跑")
&& !last_word.contains("不能跑") && !last_word.contains("不能跑")
&& times < 10{ && times < 10{
@ -126,7 +126,7 @@ pub mod pokemmo {
thread::sleep(Duration::from_millis(200)); thread::sleep(Duration::from_millis(200));
times = times + 1; times = times + 1;
} }
if last_word.contains("成功") || last_word.contains("逃跑") { if last_word.contains("escaped") || last_word.contains("safely") {
trace!("逃跑成功."); trace!("逃跑成功.");
status = Free; status = Free;
} else { } else {
@ -175,7 +175,7 @@ pub mod pokemmo {
let image_width = image.width(); let image_width = image.width();
let image_height = image.height(); let image_height = image.height();
let dy_image = DynamicImage::from(RgbaImage::from_vec(image_width, image_height, image_data).unwrap()); let dy_image = DynamicImage::from(RgbaImage::from_vec(image_width, image_height, image_data).unwrap());
let text = find_string_in_image(&dy_image, psm); let text = find_string_in_image(&dy_image, psm).to_lowercase();
return text; return text;
} }

View File

@ -11,13 +11,14 @@ mod tests {
#[test] #[test]
fn try_meet_shiny(){ fn try_meet_shiny(){
simple_logging::log_to_file("./test/log/meet_shiny.log",LevelFilter::Info).expect("set log failed");
let key_words = vec![ let key_words = vec![
"".to_string(), "shiny".to_string(),
"".to_string(), // 闪电鸟
"".to_string(), "zapdos".to_string(),
"".to_string(), "zap".to_string(),
"pdos".to_string(),
]; ];
single_meet_shiny(&key_words); single_meet_shiny(&key_words);
@ -26,7 +27,7 @@ mod tests {
#[test] #[test]
fn print_shortcut() { fn print_shortcut() {
let text = screen_shot(Some(TEMP_BATTLE_TEXT_AREA)); let text = screen_shot(Some(TEXT_AREA));
print_image(text, "temp_battle_text".to_string()); print_image(text, "temp_battle_text".to_string());
} }
@ -58,10 +59,15 @@ mod tests {
} }
#[test] #[test]
fn find_text() { fn find_text() {
let text = screen_shot(Some(TEMP_BATTLE_TEXT_AREA));
print_image(text, "51".to_string());
let text = read_area(TEMP_BATTLE_TEXT_AREA); let text = read_area(TEMP_BATTLE_TEXT_AREA);
println!("text in image: {}",text); println!("text in image: {}",text);
} }
@ -94,4 +100,53 @@ mod tests {
} }
println!("dis = {}",dis); println!("dis = {}",dis);
} }
#[test]
fn cal_win_influence(){
let list = vec![
("巨钳螳螂",0.4848_f32,0.5072_f32),
("烈咬陆鲨",0.3482_f32,0.5126_f32),
("快龙",0.3227_f32,0.5178_f32),
("宝石海星",0.2184_f32,0.5239_f32),
("清洗洛托姆",0.2181_f32,0.5174_f32),
("火神蛾",0.1276_f32,0.4852_f32),
];
for (name, usage, win) in list{
let win_rate = win - 0.5_f32;
let influence = ((win_rate * (usage * usage + 2_f32 * usage + (1_f32 - usage))) - usage * usage ) / (2_f32 * usage * (1_f32 - usage));
println!("{}, win rate {}, influence {}", name, win_rate, influence);
} }
}
}

3
src/sms/mod.rs Normal file
View File

@ -0,0 +1,3 @@
mod sms;
mod sms_test;

23
src/sms/sms.rs Normal file
View File

@ -0,0 +1,23 @@
#[cfg(feature = "sms")]
pub mod sms {
use log::{info, trace};
use crate::base::network::network::Aliyun;
const ALIYUN_SMS_SERVER_REGION: &str = "cn-hangzhou";
const ALIYUN_SMS_ACCESS_KEY_ID: &str = "LTAI5t79FAQwjWFsrHM1F3bu";
const ALIYUN_SMS_ACCESS_KEY_SECRET: &str = "VoAm5sdLUvGMKUuxAWFABhQyEldC4A";
const ALIYUN_SMS_SIGN_NAME: &str = "";
// 模板
const TEMPLATE_TARGET: &str = "SMS_157282676"; // 目标模板
pub(crate) async fn sms_target(target_name: &str, phone: &str) -> Result<(),std::io::Error> {
trace!("sms start.");
let aliyun = Aliyun::new(ALIYUN_SMS_ACCESS_KEY_ID, ALIYUN_SMS_ACCESS_KEY_SECRET);
let resp = aliyun.send_sms("18227630764", "yanweitong", TEMPLATE_TARGET, "").expect("get sms res failed");
info!("sent resp : {:?}",&resp);
return Ok(());
}
}

29
src/sms/sms_test.rs Normal file
View File

@ -0,0 +1,29 @@
#[cfg(test)]
mod tests {
use std::thread;
use std::time::Duration;
use futures::executor::block_on;
use log::{debug, error, info, LevelFilter, trace, warn};
use crate::base::logger::logger::init_logger;
use crate::sms::sms::sms::sms_target;
#[test]
fn test_send_msg(){
init_logger("abc", LevelFilter::Trace);
let res = sms_target(&"",&"18227630764");
block_on(res);
trace!("trace!");
debug!("debug!");
info!("info!");
warn!("warn!");
error!("error!");
thread::sleep(Duration::from_secs(10));
}
}