flodgatt/src/api/ws.rs

47 lines
1.4 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| {
inner_ctx.ping("Ping from StreamHandler");
},
);
2019-02-15 10:22:35 +01:00
}
// This appears to be an echo server based on the actix_web documentation
// We won't actually need echo functionality in the final server
2019-02-11 21:00:07 +01:00
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
debug!("Message {:?}", msg);
let red = ctx
.state()
.redis
.send(Command(RespValue::SimpleString("GET".into())));
2019-02-15 10:22:35 +01:00
2019-02-11 21:00:07 +01:00
match msg {
ws::Message::Pong(msg) => debug!("matched: {}", 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
}