1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
//! WsConnection struct
use core::fmt::{Debug, Formatter};
use ewebsock::{WsEvent, WsMessage, WsReceiver, WsSender};
use std::vec;
use crate::interface::interface_types::InterfaceTrait;
use crate::interface::types::BaseMessage;
use crate::tramex_error;
use crate::{data::Data, errors::TramexError};
use crate::interface::{layer::Layers, log_get::LogGet, types::WebSocketLog};
/// WsConnection struct
pub struct WsConnection {
/// WebSocket sender
pub ws_sender: WsSender,
/// WebSocket receiver
pub ws_receiver: WsReceiver,
/// Message ID
pub msg_id: u64,
/// Connecting flag
pub connecting: bool,
/// Asking size max
pub asking_size_max: u64,
/// Available flag
pub available: bool,
/// Name of the receiver
pub name: String,
}
impl WsConnection {
/// Create a new WsConnection
pub fn new(ws_sender: WsSender, ws_receiver: WsReceiver) -> Self {
Self {
ws_sender,
ws_receiver,
msg_id: 1,
connecting: true,
asking_size_max: 1024,
available: true,
name: "".to_string(),
}
}
/// Connect to a WebSocket
/// # Errors
/// Return an error as String if the connection failed - see [`ewebsock::connect_with_wakeup`] for more details
pub fn connect(url: &str, wakeup: impl Fn() + Send + Sync + 'static) -> Result<(WsSender, WsReceiver), String> {
let options = ewebsock::Options::default();
ewebsock::connect_with_wakeup(url, options, wakeup)
}
/// Try to close the ws
/// # Errors
/// Return an error if its fail see [`ewebsock::WsSender::close`] for more details
pub fn close_impl(&mut self) -> Result<(), TramexError> {
if let Err(err) = self.ws_sender.close() {
log::error!("Error closing WebSocket: {}", err);
return Err(tramex_error!(
err.to_string(),
crate::errors::ErrorCode::WebSocketErrorClosing
));
}
Ok(())
}
}
impl InterfaceTrait for WsConnection {
fn get_more_data(&mut self, layer_list: Layers, _data: &mut Data) -> Result<(), Vec<TramexError>> {
let msg = LogGet::new(self.msg_id, layer_list, self.asking_size_max);
log::debug!("Sending message: {:?}", msg);
match serde_json::to_string(&msg) {
Ok(msg_stringed) => {
log::debug!("{}", msg_stringed);
self.ws_sender.send(WsMessage::Text(msg_stringed));
self.msg_id += 1;
}
Err(err) => {
log::error!("Error encoding message: {:?}", err);
return Err(vec![tramex_error!(
err.to_string(),
crate::errors::ErrorCode::WebSocketErrorEncodingMessage
)]);
}
}
Ok(())
}
fn close(&mut self) -> Result<(), TramexError> {
self.close_impl()
}
}
impl WsConnection {
/// Try to receive data
/// # Errors
/// Return an error if the data is not received correctly
pub fn try_recv(&mut self, data: &mut Data) -> Result<(), Vec<TramexError>> {
while let Some(event) = self.ws_receiver.try_recv() {
self.connecting = false;
match event {
WsEvent::Message(msg) => {
self.available = true;
match msg {
WsMessage::Text(event_text) => {
let decoded: Result<WebSocketLog, serde_json::Error> = serde_json::from_str(&event_text);
match decoded {
Ok(decoded_data) => {
let mut errors = vec![];
for one_log in decoded_data.logs {
match one_log.extract_data() {
Ok(trace) => {
data.events.push(trace);
}
Err(err) => {
log::error!("Error while extracting data: {:?}", err);
errors.push(err);
}
}
}
if !errors.is_empty() {
return Err(errors);
}
}
Err(_err) => {
let decoded_base: Result<BaseMessage, serde_json::Error> =
serde_json::from_str(&event_text);
match decoded_base {
Ok(decoded_data) => {
if decoded_data.message == "ready" {
log::debug!("Received ready message");
}
log::debug!("Received BaseMessage: {:?}", decoded_data);
self.name = decoded_data.name;
}
Err(err) => {
log::error!("Error decoding message: {:?}", err);
log::error!("Message: {:?}", event_text);
return Err(vec![tramex_error!(
err.to_string(),
crate::errors::ErrorCode::WebSocketErrorDecodingMessage
)]);
}
}
}
}
}
WsMessage::Unknown(str_error) => {
log::error!("Unknown message: {:?}", str_error);
return Err(vec![tramex_error!(
str_error,
crate::errors::ErrorCode::WebSocketUnknownMessageReceived
)]);
}
WsMessage::Binary(bin) => {
log::error!("Unknown binary message: {:?}", bin);
return Err(vec![tramex_error!(
format!("Unknown binary message: {:?}", bin),
crate::errors::ErrorCode::WebSocketUnknownBinaryMessageReceived
)]);
}
_ => {
log::debug!("Received Ping-Pong")
}
}
}
WsEvent::Opened => {
self.available = true;
log::debug!("WebSocket opened");
}
WsEvent::Closed => {
self.available = false;
log::debug!("WebSocket closed");
return Err(vec![tramex_error!(
"WebSocket closed".to_string(),
crate::errors::ErrorCode::WebSocketClosed
)]);
}
WsEvent::Error(str_err) => {
self.available = false;
log::error!("WebSocket error: {:?}", str_err);
return Err(vec![tramex_error!(str_err, crate::errors::ErrorCode::WebSocketError)]);
}
}
}
Ok(())
}
}
impl Debug for WsConnection {
fn fmt(&self, formatter: &mut Formatter<'_>) -> core::fmt::Result {
return formatter
.debug_struct("Interface")
.field("ws_sender", &"Box<WsSender>")
.field("ws_receiver", &"Box<WsReceiver>")
.field("connecting", &self.connecting)
.finish();
}
}
impl Drop for WsConnection {
fn drop(&mut self) {
log::debug!("Cleaning WsConnection");
if let Err(err) = self.ws_sender.close() {
log::error!("Error closing WebSocket: {}", err);
}
}
}