Просмотр исходного кода

map: implemented poll() which makes get_info request every 1 sec

lunar-mining 4 лет назад
Родитель
Сommit
e0f7d538d7
3 измененных файлов с 48 добавлено и 33 удалено
  1. 3 0
      Cargo.lock
  2. 3 0
      bin/map/Cargo.toml
  3. 42 33
      bin/map/src/main.rs

+ 3 - 0
Cargo.lock

@@ -2820,9 +2820,12 @@ dependencies = [
 name = "map"
 version = "0.3.0"
 dependencies = [
+ "async-channel",
  "async-std",
  "darkfi",
+ "easy-parallel",
  "log",
+ "num_cpus",
  "rand 0.6.5",
  "serde_json",
  "smol",

+ 3 - 0
bin/map/Cargo.toml

@@ -15,10 +15,13 @@ tui = "0.16.0"
 # Async
 smol = "1.2.4"
 async-std = {version = "1.10.0", features = ["attributes"]}
+easy-parallel = "3.2.0"
+async-channel = "1.6.1"
 
 # Misc
 rand = "0.6.5"
 log = "0.4.14"
+num_cpus = "1.13.1"
 
 # Encoding and parsing
 serde_json = "1.0.74"

+ 42 - 33
bin/map/src/main.rs

@@ -5,11 +5,15 @@
 use darkfi::{
     error::{Error, Result},
     rpc::{jsonrpc, jsonrpc::JsonResult},
+    util::async_util,
 };
 
+use async_std::sync::Arc;
+use easy_parallel::Parallel;
 use log::debug;
 use serde_json::{json, Value};
-use std::{io, io::Read, time::Duration};
+use smol::Executor;
+use std::{io, io::Read};
 use termion::{async_stdin, event::Key, input::TermRead, raw::IntoRawMode};
 use tui::{
     backend::{Backend, TermionBackend},
@@ -53,7 +57,7 @@ impl Map {
 
     // --> {"jsonrpc": "2.0", "method": "say_hello", "params": [], "id": 42}
     // <-- {"jsonrpc": "2.0", "result": "hello world", "id": 42}
-    async fn say_hello(&self) -> Result<Value> {
+    async fn _say_hello(&self) -> Result<Value> {
         let req = jsonrpc::request(json!("say_hello"), json!([]));
         Ok(self.request(req).await?)
     }
@@ -66,45 +70,56 @@ impl Map {
     }
 }
 
-async fn start() -> Result<()> {
-    let client = Map::new("tcp://127.0.0.1:8000".to_string());
-    // call this every 1 second (poll)
-    let reply = client.get_info().await?;
-    println!("Server replied: {}", &reply.to_string());
-    Ok(())
-}
-
 #[async_std::main]
 async fn main() -> Result<()> {
-    // Set up terminal output
     let stdout = io::stdout().into_raw_mode()?;
     let backend = TermionBackend::new(stdout);
     let mut terminal = Terminal::new(backend)?;
 
-    // we're not using this yet
-    let tick_rate = Duration::from_millis(250);
-
-    // start rpc
-    start().await?;
+    terminal.clear()?;
 
-    // create the app and run it
     let app = App::new();
-    let res = run_app(&mut terminal, app, tick_rate);
 
-    terminal.clear()?;
+    let nthreads = num_cpus::get();
+    let (signal, shutdown) = async_channel::unbounded::<()>();
+
+    let ex = Arc::new(Executor::new());
+    let ex2 = ex.clone();
+
+    let (_, result) = Parallel::new()
+        .each(0..nthreads, |_| smol::future::block_on(ex.run(shutdown.recv())))
+        // Run the main future on the current thread.
+        .finish(|| {
+            smol::future::block_on(async move {
+                start(ex2.clone()).await?;
+                run_app(&mut terminal, app).await?;
+                drop(signal);
+                Ok::<(), darkfi::Error>(())
+            })
+        });
+
+    result
+}
 
-    if let Err(err) = res {
-        println!("{:?}", err)
-    }
+async fn start(ex: Arc<Executor<'_>>) -> Result<()> {
+    let client = Map::new("tcp://127.0.0.1:8000".to_string());
+
+    ex.spawn(async {
+        poll(client).await;
+    })
+    .detach();
 
     Ok(())
 }
 
-fn run_app<B: Backend>(
-    terminal: &mut Terminal<B>,
-    mut app: App,
-    _tick_rate: Duration,
-) -> io::Result<()> {
+async fn poll(client: Map) -> Result<()> {
+    loop {
+        client.get_info().await?;
+        async_util::sleep(1).await;
+    }
+}
+
+async fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
     let mut asi = async_stdin();
 
     terminal.clear()?;
@@ -112,7 +127,6 @@ fn run_app<B: Backend>(
     app.node_list.state.select(Some(0));
 
     app.node_info.index = 0;
-    //let mut last_tick = Instant::now();
 
     loop {
         terminal.draw(|f| ui::ui(f, &mut app))?;
@@ -134,10 +148,5 @@ fn run_app<B: Backend>(
                 _ => (),
             }
         }
-
-        //if last_tick.elapsed() >= tick_rate {
-        //    app.clone().update();
-        //    last_tick = Instant::now();
-        //}
     }
 }