pub mod env;
use serde::{Deserialize, Serialize};
use crate::{
__private::send_ws_msg,
events::Events,
events::{CallAction, MethodOrId},
};
#[derive(Debug, Serialize, Deserialize)]
pub struct Schedule {
#[serde(flatten)]
pub method: MethodOrId,
pub interval: u64,
#[serde(default)]
pub delay: u64,
}
impl Schedule {
pub fn by_method_id(method_id: u32, interval: u64, delay: u64) -> Self {
Self {
method: MethodOrId::ById { method_id },
interval,
delay,
}
}
pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
serde_json::to_vec(self)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
serde_json::from_slice(bytes)
}
pub fn get_action(&self) -> CallAction {
CallAction::new(self.method.clone(), serde_json::Value::Null)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WsConfig {
pub url: String,
pub reconnect: bool,
pub ping_interval: u64,
#[serde(default)]
pub binary: bool,
}
pub trait WebsocketHandler {
type Err: std::fmt::Display + std::fmt::Debug + Send + Sync;
fn open_ws(&self) -> WsConfig;
fn on_message(&mut self, msg: Vec<u8>) -> Result<Option<Events>, Self::Err>;
fn on_open(&mut self) -> Result<Option<Events>, Self::Err> {
Ok(None)
}
fn on_error(&mut self) -> Result<Option<Events>, Self::Err> {
crate::error!("Websocket error - connection closed.");
self.on_close()
}
fn on_close(&mut self) -> Result<Option<Events>, Self::Err> {
Ok(None)
}
fn send_ws_msg(&self, msg: Vec<u8>) -> Result<(), anyhow::Error> {
send_ws_msg(msg)
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Init {
pub schedules: Vec<Schedule>,
pub ws_config: Option<WsConfig>,
}
impl Init {
pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
serde_json::to_vec(self)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
serde_json::from_slice(bytes)
}
}