flodgatt/src/api/ws.rs

39 lines
1.1 KiB
Rust
Raw Normal View History

2019-02-15 10:22:35 +01:00
use crate::{common::HEARTBEAT_INTERVAL_SECONDS, AppState};
use actix::{Actor, AsyncContext, StreamHandler};
use actix_redis::{Command, RespValue};
2019-02-11 21:00:07 +01:00
use actix_web::{ws, HttpRequest, Responder};
2019-02-15 10:22:35 +01:00
use log::{debug, info};
use std::time::Duration;
2019-02-11 18:58:51 +01:00
2019-02-11 21:00:07 +01:00
/// Define http actor
struct WebsocketActor;
impl Actor for WebsocketActor {
2019-02-15 10:22:35 +01:00
type Context = ws::WebsocketContext<Self, AppState>;
2019-02-11 21:00:07 +01:00
}
/// Handler for ws::Message message
impl StreamHandler<ws::Message, ws::ProtocolError> for WebsocketActor {
2019-02-15 10:22:35 +01:00
fn started(&mut self, ctx: &mut Self::Context) {
ctx.run_interval(Duration::from_secs(HEARTBEAT_INTERVAL_SECONDS), |_, inner_ctx| {
2019-02-19 20:29:32 +01:00
inner_ctx.ping("");
2019-02-15 10:22:35 +01:00
});
}
2019-02-11 21:00:07 +01:00
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
debug!("Message {:?}", msg);
2019-02-15 10:22:35 +01:00
let red = ctx.state().redis.send(Command(RespValue::SimpleString("GET".into())));
2019-02-11 21:00:07 +01:00
match msg {
2019-02-15 10:22:35 +01:00
ws::Message::Pong(msg) => debug!("{}", msg),
2019-02-11 21:00:07 +01:00
ws::Message::Text(text) => ctx.text(text),
_ => (),
}
}
}
2019-02-15 10:22:35 +01:00
pub fn index(req: HttpRequest<AppState>) -> impl Responder {
2019-02-11 21:00:07 +01:00
ws::start(&req, WebsocketActor)
2019-02-11 18:58:51 +01:00
}