unmp-center 0.1.2

unmp data center
Documentation
use crate::var::{self, VarChgCb};
use spin::RwLock;
use unmp::id::Id;
use unmp_center_core::{Kind, Status};

static LISTENER: RwLock<Listener> = RwLock::new(Listener::new());

type ErrorCb = fn(Kind, Status);
type GetIdCb = fn(&Id, &[u8; 8], &[u8; 8]);
type LoginCb = fn();
type GetTimestampCb = fn(u64);
type EnterBindCb = fn(&[u8; 4]);
type BindCb = fn(&Id, &[u8; 8]);
type UnbindCb = fn(&Id);

#[derive(Default)]
struct Listener {
    error: Option<ErrorCb>,
    get_id: Option<GetIdCb>,
    login: Option<LoginCb>,
    get_timestamp: Option<GetTimestampCb>,
    enter_bind: Option<EnterBindCb>,
    bind: Option<BindCb>,
    unbind: Option<UnbindCb>,
}
impl Listener {
    const fn new() -> Listener {
        Listener {
            error: None,
            get_id: None,
            login: None,
            get_timestamp: None,
            enter_bind: None,
            bind: None,
            unbind: None,
        }
    }
}

pub fn on_error(cb: ErrorCb) {
    LISTENER.write().error = Some(cb);
}
pub(crate) fn emit_error(kind: Kind, status: Status) {
    if let Some(cb) = LISTENER.read().error {
        cb(kind, status);
    }
}
pub fn on_getid(cb: GetIdCb) {
    LISTENER.write().get_id = Some(cb);
}
pub(crate) fn emit_getid(id: &Id, private_key: &[u8; 8], public_key: &[u8; 8]) {
    if let Some(cb) = LISTENER.read().get_id {
        cb(id, private_key, public_key);
    }
}
pub fn on_login(cb: LoginCb) {
    LISTENER.write().login = Some(cb);
}
pub(crate) fn emit_login() {
    if let Some(cb) = LISTENER.read().login {
        cb();
    }
}
pub fn on_get_timestamp(cb: GetTimestampCb) {
    LISTENER.write().get_timestamp = Some(cb);
}
pub(crate) fn emit_get_timestamp(timestamp: u64) {
    if let Some(cb) = LISTENER.read().get_timestamp {
        cb(timestamp);
    }
}
pub fn on_change_actual(cb: VarChgCb) {
    var::on_actual_chg(cb);
}
pub fn on_change_target(cb: VarChgCb) {
    var::on_target_chg(cb);
}
pub fn on_enter_bind(cb: EnterBindCb) {
    LISTENER.write().enter_bind = Some(cb);
}
pub(crate) fn emit_enter_bind(code: &[u8; 4]) {
    if let Some(cb) = LISTENER.read().enter_bind {
        cb(code);
    }
}
pub fn on_bind(cb: BindCb) {
    LISTENER.write().bind = Some(cb);
}
pub(crate) fn emit_bind(id: &Id, public_key: &[u8; 8]) {
    if let Some(cb) = LISTENER.read().bind {
        cb(id, public_key);
    }
}
pub fn on_unbind(cb: UnbindCb) {
    LISTENER.write().unbind = Some(cb);
}
pub(crate) fn emit_unbind(id: &Id) {
    if let Some(cb) = LISTENER.read().unbind {
        cb(id);
    }
}