Skip to content

Commit

Permalink
use global settings
Browse files Browse the repository at this point in the history
  • Loading branch information
mdonoughe committed Mar 2, 2019
1 parent 6f63f4a commit 105259c
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 98 deletions.
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ serde_derive = "1.0"
serde_json = "1.0"
slog = { version = "2.4", features = ["max_level_trace", "release_max_level_info"] }
sloggers = "0.3"
streamdeck-rs = "0.1.0"
streamdeck-rs = { git = "https://github.com/mdonoughe/streamdeck-rs", branch = "sdk2" }
tokio = "0.1.14"
25 changes: 0 additions & 25 deletions examples/sbzdeck.json

This file was deleted.

6 changes: 5 additions & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"UUID": "io.github.mdonoughe.sbzdeck.selectOutput"
}
],
"SDKVersion": 2,
"Author": "Matthew Donoughe <[email protected]>",
"Category": "sbzdeck",
"CategoryIcon": "categoryIcon",
Expand All @@ -32,5 +33,8 @@
"Platform": "windows",
"MinimumVersion": "10"
}
]
],
"Software": {
"MinimumVersion": "4.1"
}
}
114 changes: 66 additions & 48 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ mod sb;
mod settings;
mod types;

use crate::settings::SerdeCardSettings;
use crate::types::*;
use futures::prelude::*;
use futures::sync::mpsc;
Expand All @@ -33,9 +34,15 @@ use tokio::prelude::*;

const ACTION_SELECT_OUTPUT: &str = "io.github.mdonoughe.sbzdeck.selectOutput";

fn connect() -> impl Future<Item = StreamDeckSocket<Empty, Empty, Empty>, Error = ConnectError> {
let params = RegistrationParams::from_args(env::args()).unwrap();
StreamDeckSocket::<Empty, Empty, Empty>::connect(params.port, params.event, params.uuid)
fn connect(
params: &RegistrationParams,
) -> impl Future<Item = StreamDeckSocket<SerdeCardSettings, Empty, Empty, Empty>, Error = ConnectError>
{
StreamDeckSocket::<SerdeCardSettings, Empty, Empty, Empty>::connect(
params.port,
params.event.to_string(),
params.uuid.to_string(),
)
}

fn handle_new_action(logger: &Logger, state: &State, context: &str, action_state: u8) {
Expand Down Expand Up @@ -174,29 +181,43 @@ fn handle_press(

fn handle_message(
logger: &Logger,
message: &Message<Empty, Empty>,
message: Message<SerdeCardSettings, Empty, Empty>,
state: &State,
trigger_save: &mut mpsc::Sender<()>,
) -> Result<(), ()> {
match &message {
match message {
Message::WillAppear {
action,
context,
payload,
ref action,
ref context,
ref payload,
..
} if action == ACTION_SELECT_OUTPUT => {
handle_new_action(logger, state, context, payload.state)
handle_new_action(logger, state, &context, payload.state)
}
Message::WillDisappear {
action, context, ..
} if action == ACTION_SELECT_OUTPUT => handle_remove_action(state, context),
ref action,
ref context,
..
} if action == ACTION_SELECT_OUTPUT => handle_remove_action(state, &context),
Message::KeyUp {
action,
context,
payload,
ref action,
ref context,
ref payload,
..
} if action == ACTION_SELECT_OUTPUT => {
handle_press(logger, state, context, payload, trigger_save)
handle_press(logger, state, &context, &payload, trigger_save)
}
Message::DidReceiveGlobalSettings { payload, .. } => {
match settings::load(payload.settings) {
Ok(settings) => {
let mut state = state.lock().unwrap();
state.settings = settings;
info!(logger, "loaded settings");
}
Err(error) => {
error!(logger, "error loading settings: {:?}", error);
}
}
}
_ => {}
}
Expand All @@ -206,34 +227,14 @@ fn handle_message(
fn main() {
let logger = logger::create();
info!(logger, "launched {:?}", env::args().collect::<Vec<_>>());

let settings = match settings::load() {
Ok(settings) => settings,
Err(error) => {
if error.is_io() {
let error = std::io::Error::from(error);
match error.kind() {
std::io::ErrorKind::NotFound => {
warn!(logger, "settings file was not found");
}
_ => {
error!(logger, "failed to load settings: {:?}", error);
}
}
} else {
error!(logger, "failed to load settings: {:?}", error);
}
CardSettings::default()
}
};
debug!(logger, "settings: {:?}", settings);
let params = RegistrationParams::from_args(env::args()).unwrap();

let (out_sink, out_stream) = mpsc::channel(1);
let mut state = RawState {
output: None,
contexts: BTreeSet::new(),
out: out_sink,
settings,
out: out_sink.clone(),
settings: CardSettings::default(),
};

match sb::get_current_profile(&logger) {
Expand All @@ -259,16 +260,27 @@ fn main() {
let (mut trigger_save, save_trigger) = mpsc::channel(0);
let state_save = state.clone();
let save_log = logger.clone();
let save_sink = out_sink.clone();
let save_context = params.uuid.clone();
let save = save_trigger
.throttle(Duration::from_secs(5))
.for_each(move |_| {
debug!(save_log, "saving…");
let settings = { settings::prepare_for_save(&state_save.lock().unwrap().settings) };
match settings::save(&settings) {
Ok(_) => debug!(save_log, "settings saved"),
Err(error) => error!(save_log, "settings could not be saved: {:?}", error),
}
Ok(())
let log = save_log.clone();
save_sink
.clone()
.send(MessageOut::SetGlobalSettings {
context: save_context.to_string(),
payload: settings,
})
.then(move |r| {
match r {
Ok(_) => debug!(log, "settings saved"),
Err(error) => error!(log, "settings could not be saved: {:?}", error),
}
Ok(())
})
});

let state_events = state.clone();
Expand Down Expand Up @@ -337,25 +349,31 @@ fn main() {
});

let logger_e = logger.clone();
let test = connect()
let get_settings_context = params.uuid.clone();
let test = connect(&params)
.map_err(move |e| crit!(logger_e, "connection failed {:?}", e))
.and_then(move |s| {
info!(logger, "connected!");
let (sink, stream) = s.split();

let logger_e = logger.clone();
tokio::spawn(
sink.send_all(out_stream.map_err(|_| unreachable!()))
.map_err(move |e| error!(logger_e, "failed to send message: {:?}", e))
.map(|_| ()),
stream::once(Ok(MessageOut::GetGlobalSettings {
context: get_settings_context,
}))
.chain(out_stream)
.forward(
sink.sink_map_err(move |e| error!(logger_e, "failed to send message: {:?}", e)),
)
.map(|_| ()),
);

let logger_e = logger.clone();
stream
.map_err(move |e| crit!(logger_e, "receive failed {:?}", e))
.for_each(move |message| {
debug!(logger, "received {:?}", message);
handle_message(&logger, &message, &state, &mut trigger_save)
handle_message(&logger, message, &state, &mut trigger_save)
})
});
tokio::run(
Expand Down
23 changes: 4 additions & 19 deletions src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,23 @@ use crate::types::*;
use indexmap::IndexMap;
use sbz_switch::soundcore::SoundCoreParamValue;
use serde_derive::{Deserialize, Serialize};
use std::env;
use std::fs::File;

#[derive(Default, Deserialize, Serialize)]
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct SerdeProfile {
pub volume: Option<f32>,
#[serde(default)]
pub parameters: serde_json::Map<String, serde_json::Value>,
}

#[derive(Default, Deserialize, Serialize)]
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct SerdeProfiles {
#[serde(default)]
pub headphones: SerdeProfile,
#[serde(default)]
pub speakers: SerdeProfile,
}

#[derive(Default, Deserialize, Serialize)]
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct SerdeCardSettings {
#[serde(default)]
pub selected_parameters: serde_json::Map<String, serde_json::Value>,
Expand Down Expand Up @@ -62,12 +60,7 @@ fn convert_to_soundcore(
.collect()
}

pub fn load() -> Result<CardSettings, serde_json::Error> {
let mut path = env::current_exe().unwrap_or_default();
path.pop();
path.push("sbzdeck.json");
let file = File::open(path).map_err(serde_json::Error::io)?;
let de: SerdeCardSettings = serde_json::from_reader(file)?;
pub fn load(de: SerdeCardSettings) -> Result<CardSettings, serde_json::Error> {
Ok(CardSettings {
selected_parameters: de
.selected_parameters
Expand Down Expand Up @@ -162,11 +155,3 @@ pub fn prepare_for_save(settings: &CardSettings) -> SerdeCardSettings {
},
}
}

pub fn save(settings: &SerdeCardSettings) -> Result<(), serde_json::Error> {
let mut path = env::current_exe().unwrap_or_default();
path.pop();
path.push("sbzdeck.json");
let file = File::create(path).map_err(serde_json::Error::io)?;
serde_json::to_writer_pretty(file, settings)
}
3 changes: 2 additions & 1 deletion src/types.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::settings::SerdeCardSettings;
use futures::sync::mpsc;
use indexmap::{IndexMap, IndexSet};
use sbz_switch::soundcore::SoundCoreParamValue;
Expand Down Expand Up @@ -70,7 +71,7 @@ impl IndexMut<Output> for Profiles {
pub struct RawState {
pub output: Option<Output>,
pub contexts: BTreeSet<String>,
pub out: mpsc::Sender<MessageOut<Empty, Empty>>,
pub out: mpsc::Sender<MessageOut<SerdeCardSettings, Empty, Empty>>,
pub settings: CardSettings,
}

Expand Down

0 comments on commit 105259c

Please sign in to comment.