diff rust/src/main.rs @ 634:a5721c02d3ee rust

build succeeds
author Matt Johnston <matt@ucc.asn.au>
date Sun, 22 Sep 2019 20:35:40 +0800
parents 490e9e15b98c
children 4424a8b30f9c
line wrap: on
line diff
--- a/rust/src/main.rs	Wed Sep 04 23:24:13 2019 +0800
+++ b/rust/src/main.rs	Sun Sep 22 20:35:40 2019 +0800
@@ -1,10 +1,10 @@
+#![feature(async_closure)]
 #[macro_use] extern crate log;
 // riker has its own logging?
 //extern crate env_logger;
 
 #[macro_use] extern crate lazy_static;
 
-use sensor::Sensor;
 
 mod config;
 mod sensor;
@@ -12,153 +12,98 @@
 mod types;
 mod params;
 
-use types::*;
-use config::Config;
+use crate::config::Config;
+
+use riker::actors::*;
 
-fn run(config: &Config, nowait: bool, testmode: bool) {
+use structopt::StructOpt;
 
-    let mut core = Core::new().unwrap();
-    let handle = core.handle();
+fn run(cf: Config, nowait: bool, testmode: bool) {
 
-    let params = params::Params::load(&config);
-    let mut fridge = fridge::Fridge::new(&config, nowait, params, &handle);
+    let sys = ActorSystem::new().unwrap();
+    let props = Props::new_args(params::ParamWaiter::new, cf.clone());
+    sys.actor_of(props, "paramwaiter").unwrap();
 
-    let sensor_stream = if testmode {
-        sensor::TestSensor::new(config).stream(&handle)
+    if testmode {
+        let props = Props::new_args(sensor::TestSensor::new, cf.clone());
+        sys.actor_of(props, "sensor").unwrap()
     } else {
-        sensor::OneWireSensor::new(config).stream(&handle)
+        let props = Props::new_args(sensor::OneWireSensor::new, cf.clone());
+        sys.actor_of(props, "sensor").unwrap()
     };
 
-    // Send the sensors of interest to the fridge (fridge_reading_s),
-    // while streaming them all to the web sender.
-    let (fridge_reading_s, fridge_reading_r) = mpsc::channel(1);
-    let fridge_reading_r = fridge_reading_r.map_err(|e| TemplogError::new("Problem with fridge_reading_r channel"));
-    let sensor_stream = sensor_stream.map(|r| {
-        debug!("sensors {:?}", r);
-        let msg = fridge::Message::Sensor {
-            wort: r.get_temp(&config.WORT_NAME), 
-            fridge: r.get_temp(&config.FRIDGE_NAME)
-        };
-        let t = fridge_reading_s.clone().send(msg)
-                    .map(|_| ())
-                    .map_err(|e| {
-                        warn!("Send error in fridge_reading_s: {}", e.to_string());
-                        ()
-                    });
-        handle.spawn(t);
-        r
-    });
-
-    let param_stream = params::ParamWaiter::stream(config.clone(), handle.clone());
-    let param_stream = param_stream.map(|p| {
-            fridge::Message::Params(p)
-        });
-
-    let timeouts = fridge.wakeups();
-
-    // forward all the different types of messages to the fridge
-    let all_fridge = param_stream.select(timeouts).select(fridge_reading_r).forward(fridge) .map(|_| () );
-
-    let all_readings = sensor_stream.for_each(|_| Ok(()));
-
-    // run forever
-    let all = all_fridge.select(all_readings);
-    core.run(all).ok();
+    let props = Props::new_args(fridge::Fridge::new_actor, (cf.clone(), nowait));
+    sys.actor_of(props, "fridge").unwrap();
 }
 
-const USAGE: &'static str = "\
-Wort Temperature
-Matt Johnston 2017 [email protected]
-Usage: wort-templog [--help] [--new] [--daemon] [--debug] [--test] [--defconf] [--thisconf] [--nowait]
+#[derive(Debug, StructOpt)]
+#[structopt(name = "Wort Temperature", about = "Matt Johnston 2019 [email protected]")]
+struct Opt {
+    /// Replace existing running instance
+    #[structopt(long)]
+    new: bool,
+
+    /// Run in background
+    #[structopt(short = "D", long)]
+    daemon: bool,
 
-Options:
-  -h, --help
-  --new         Replace existing running instance
-  -D, --daemon  Run in background
-  -d, --debug
-  -t, --test    Use fake sensors etc
-  --nowait      Skip initial fridge wait
-  --defconf     Print default config (customise in local.conf)
-  --thisconf    Print used config
-";
+    #[structopt(short, long)]
+    debug: bool,
+
+    /// Use fake sensors etc
+    #[structopt(long)]
+    test: bool,
 
-#[derive(RustcDecodable)]
-struct Args {
-    flag_new: bool,
-    flag_daemon: bool,
-    flag_debug: bool,
-    flag_test: bool,
-    flag_defconf: bool,
-    flag_thisconf: bool,
-    flag_nowait: bool,
+    /// Skip initial fridge wait
+    #[structopt(long)]
+    nowait: bool,
+
+    /// Print default config (customise in local.conf)
+    #[structopt(long)]
+    defconf: bool,
 }
 
-fn handle_args() -> Args {
-    let args: Args = docopt::Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit());
+fn handle_args() -> Opt {
+    let args = Opt::from_args();
 
-    if args.flag_defconf {
+    if args.defconf {
         println!("Default configuration:\n{}\n\n{}",
             "(custom options go in local.conf)",
-            config::Config::default().to_toml_string());
+            config::Config::default_toml());
         std::process::exit(0);
     }
     args
 }
 
-fn setup_log(debug: bool) {
-    let loglevel = if debug {
-       log::LogLevelFilter::Debug
-    } else {
-       log::LogLevelFilter::Info
-    };
+// fn setup_log(debug: bool) {
+//     let loglevel = if debug {
+//        log::LevelFilter::Debug
+//     } else {
+//        log::LevelFilter::Info
+//     };
 
-    let format = |record: &log::LogRecord| {
-        let datefmt = "%Y-%m-%d %I:%M:%S %p";
-        let ts = time::strftime(datefmt, &time::now()).unwrap();
-        format!("{}: {} - {}", ts, record.level(), record.args())
-    };
+//     let format = |record: &log::Record| {
+//         let datefmt = "%Y-%m-%d %I:%M:%S %p";
+//             let ts = chrono::Local::now().format(datefmt);
+//         format!("{}: {} - {}", ts, record.level(), record.args())
+//     };
 
 
-    let mut builder = env_logger::LogBuilder::new();
-    builder.format(format).filter(Some("wort_templog"), loglevel);
-    builder.init().unwrap();
-}
-
-fn load_config() -> Config {
-    let nconfig = config::Config::default();
-
-    let conf_filename = "local.conf";
-    nconfig.merge_file(conf_filename)
-        .unwrap_or_else(|e| {
-            if let TemplogErrorKind::Io(ref ioe) = *e.kind() {
-                if let Some(errno) = ioe.raw_os_error() {
-                    if errno == libc::ENOENT {
-                        return nconfig;
-                    }
-                }
-            }
-
-            println!("Couldn't parse {}: {}", conf_filename, e);
-            std::process::exit(1);
-    })
-}
+//     let mut builder = env_logger::Builder::new();
+//     builder.format(format).filter(Some("wort_templog"), loglevel);
+//     builder.init().unwrap();
+// }
 
 fn main() {
 
     let args = handle_args();
-    setup_log(args.flag_debug);
+    // setup_log(args.debug);
     //env_logger::init().unwrap();
 
     info!("wort-templog");
     debug!("debug mode");
 
-    let config = load_config();
+    let config = config::Config::load().unwrap();
 
-    if args.flag_thisconf {
-        println!("Current configuration:\n\n{}",
-            config.to_toml_string());
-        std::process::exit(0);
-    }
-
-    run(&config, args.flag_nowait, args.flag_test);
+    run(config, args.nowait, args.test);
 }