Skip to content

Commit

Permalink
Add basic layer changes notifications support
Browse files Browse the repository at this point in the history
  • Loading branch information
ItayGarin committed Jun 15, 2020
1 parent 3216ef3 commit a3bc574
Show file tree
Hide file tree
Showing 5 changed files with 119 additions and 18 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ enum-iterator = {version = "0.6.0", optional = true}
[features]
sound = ["rodio", "enum-iterator"]
ipc = ["zmq"]
notify = ["zmq"]
30 changes: 30 additions & 0 deletions py/ktrl_notify_sub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/python3
import zmq
import argparse

DEFAULT_NOTIFY_PORT = 7333

def main():
parser = argparse.ArgumentParser()
parser.add_argument("--port", help="ktrl's notify port")
args = parser.parse_args()

if args.port == None:
port = DEFAULT_NOTIFY_PORT
else:
port = int(args.port)

context = zmq.Context()
endpoint = "tcp://127.0.0.1:" + str(port)
socket = context.socket(zmq.SUB)
socket.connect(endpoint)
socket.setsockopt(zmq.SUBSCRIBE, b"layer")
print("Connected to ktrl's notification server: " + endpoint)

while True:
message = socket.recv()
print("NOTIFY: [ %s ]" % message)


if __name__ == "__main__":
main()
11 changes: 8 additions & 3 deletions src/ktrl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub struct KtrlArgs {
pub assets_path: PathBuf,
pub ipc_port: usize,
pub ipc_msg: Option<String>,
pub notify_port: usize,
}

pub struct Ktrl {
Expand All @@ -46,7 +47,6 @@ pub struct Ktrl {

impl Ktrl {
pub fn new(args: KtrlArgs) -> Result<Self, std::io::Error> {

let kbd_out = match KbdOut::new() {
Ok(kbd_out) => kbd_out,
Err(err) => {
Expand All @@ -57,7 +57,13 @@ impl Ktrl {

let cfg_str = read_to_string(args.config_path)?;
let cfg = cfg::parse(&cfg_str);
let mut l_mgr = LayersManager::new(&cfg.layers, &cfg.layer_aliases, &cfg.layer_profiles);
let mut l_mgr = LayersManager::new(
&cfg.layers,
&cfg.layer_aliases,
&cfg.layer_profiles,
#[cfg(feature = "notify")]
args.notify_port,
)?;
l_mgr.init();

let th_mgr = TapHoldMgr::new(cfg.tap_hold_wait_time);
Expand Down Expand Up @@ -169,5 +175,4 @@ impl Ktrl {
ktrl.handle_key_event(&key_event)?;
}
}

}
64 changes: 54 additions & 10 deletions src/layers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ use std::collections::HashMap;
use std::convert::TryFrom;
use std::vec::Vec;

#[cfg(feature = "notify")]
use log::info;

pub use crate::actions::tap_hold::TapHoldState;
pub use crate::actions::Action;
pub use crate::effects::Effect;
Expand Down Expand Up @@ -74,6 +77,10 @@ pub struct LayersManager {
// but locks prevents layer changes globally.
// I.E not key-specific like key_locks
pub global_lock: Option<LockOwner>,

// For sending notifications about layer changes
#[cfg(feature = "notify")]
notify_socket: zmq::Socket,
}

// -------------- Implementation -------------
Expand Down Expand Up @@ -105,7 +112,9 @@ impl LayersManager {
layers: &Layers,
layer_aliases: &LayerAliases,
layer_profiles: &LayerProfiles,
) -> Self {
#[cfg(feature = "notify")]
notify_port: usize
) -> Result<Self, std::io::Error> {
let merged = init_merged();
let layers = layers.clone();
let layer_aliases = layer_aliases.clone();
Expand All @@ -116,15 +125,29 @@ impl LayersManager {
let mut layers_states = Vec::new();
layers_states.resize_with(layers_count, Default::default);

LayersManager {
merged,
layers,
layer_aliases,
layer_profiles,
layers_states,
key_locks,
global_lock: None,
}
#[cfg(feature = "notify")]
let notify_socket = {
let ctx = zmq::Context::new();
let socket = ctx.socket(zmq::PUB)?;
let endpoint = format!("tcp://127.0.0.1:{}", notify_port);
socket.bind(&endpoint)?;
info!("Sending notifications on {}", endpoint);
socket
};

Ok(
LayersManager {
merged,
layers,
layer_aliases,
layer_profiles,
layers_states,
key_locks,
global_lock: None,
#[cfg(feature = "notify")]
notify_socket
}
)
}

// ---------------- Locks -------------------------
Expand Down Expand Up @@ -198,6 +221,21 @@ impl LayersManager {
}
}

#[cfg(feature = "notify")]
fn send_notification(&mut self, index: LayerIndex, state: bool) {
let str_state = match state {
true => "on",
false => "off",
};

let msg = format!("layer {}:{}", index, str_state);
if let Err(err) = self.notify_socket.send(&msg, 0) {
warn!("Failed to send a notification. {}", err);
} else {
debug!("Sent a notification: '{}'", &msg);
}
}

pub fn get(&self, key: KeyCode) -> &MergedKey {
match &self.merged[usize::from(key)] {
Some(merged_key) => merged_key,
Expand Down Expand Up @@ -257,6 +295,9 @@ impl LayersManager {

self.layers_states[index] = true;
debug!("Turned layer {} on", index);

#[cfg(feature = "notify")]
self.send_notification(index, true);
}
}

Expand All @@ -275,6 +316,9 @@ impl LayersManager {

self.layers_states[index] = false;
debug!("Turned layer {} off", index);

#[cfg(feature = "notify")]
self.send_notification(index, false);
}
}
}
Expand Down
31 changes: 26 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const DEFAULT_CFG_PATH: &str = "/opt/ktrl/cfg.ron";
const DEFAULT_LOG_PATH: &str = "/opt/ktrl/log.txt";
const DEFAULT_ASSETS_PATH: &str = "/opt/ktrl/assets";
const DEFAULT_IPC_PORT: &str = "7331";
const DEFAULT_NOTIFY_PORT: &str = "7333";

#[doc(hidden)]
fn cli_init() -> Result<KtrlArgs, std::io::Error> {
Expand Down Expand Up @@ -75,15 +76,25 @@ fn cli_init() -> Result<KtrlArgs, std::io::Error> {
.takes_value(true),
)
.arg(
Arg::with_name("port")
.long("port")
.value_name("PORT")
Arg::with_name("ipc_port")
.long("ipc-port")
.value_name("IPC-PORT")
.help(&format!(
"TCP Port to listen on for ipc requests. Default: {}",
DEFAULT_IPC_PORT
))
.takes_value(true),
)
)
.arg(
Arg::with_name("notify_port")
.long("notify-port")
.value_name("NOTIFY-PORT")
.help(&format!(
"TCP Port where notifications will be sent. Default: {}",
DEFAULT_NOTIFY_PORT
))
.takes_value(true),
)
.arg(
Arg::with_name("msg")
.long("msg")
Expand All @@ -102,8 +113,17 @@ fn cli_init() -> Result<KtrlArgs, std::io::Error> {
let log_path = Path::new(matches.value_of("logfile").unwrap_or(DEFAULT_LOG_PATH));
let assets_path = Path::new(matches.value_of("assets").unwrap_or(DEFAULT_ASSETS_PATH));
let kbd_path = Path::new(matches.value_of("device").unwrap());
let ipc_port = matches.value_of("port").unwrap_or(DEFAULT_IPC_PORT).parse::<usize>().expect("Bad port value");
let ipc_port = matches
.value_of("ipc_port")
.unwrap_or(DEFAULT_IPC_PORT)
.parse::<usize>()
.expect("Bad ipc port value");
let ipc_msg = matches.value_of("msg").map(|x: &str| x.to_string());
let notify_port = matches
.value_of("notify_port")
.unwrap_or(DEFAULT_NOTIFY_PORT)
.parse::<usize>()
.expect("Bad notify port value");

let log_lvl = match matches.is_present("debug") {
true => LevelFilter::Debug,
Expand Down Expand Up @@ -142,6 +162,7 @@ fn cli_init() -> Result<KtrlArgs, std::io::Error> {
assets_path: assets_path.to_path_buf(),
ipc_port,
ipc_msg,
notify_port,
})
}

Expand Down

0 comments on commit a3bc574

Please sign in to comment.