Skip to content

Commit fabc88e

Browse files
committed
WIP: First working server
1 parent 58e0cfc commit fabc88e

File tree

2 files changed

+47
-72
lines changed

2 files changed

+47
-72
lines changed

src/server/handlers.rs

Lines changed: 41 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
//! Handlers for the server.
22
3+
use std::convert::Infallible;
34
// use iron::modifiers::Header;
45
// use iron::prelude::*;
56
// use iron::{headers, middleware, status};
67
use log::{debug, error, info, warn};
8+
use hyper::{Body, Request, Response, Server, StatusCode};
9+
use routerify::prelude::*;
710
// use router::Router;
811
use serde::ser::{Serialize, SerializeMap, Serializer};
912

1013
use crate::api;
11-
use crate::modifiers;
14+
//use crate::modifiers;
1215
use crate::sensors;
1316
use crate::types::RedisPool;
17+
use crate::server::SpaceapiServer;
1418

1519
#[derive(Debug)]
1620
struct ErrorResponse {
@@ -29,73 +33,51 @@ impl Serialize for ErrorResponse {
2933
}
3034
}
3135

32-
pub(crate) struct ReadHandler {
33-
status: api::Status,
34-
redis_pool: RedisPool,
35-
sensor_specs: sensors::SafeSensorSpecs,
36-
status_modifiers: Vec<Box<dyn modifiers::StatusModifier>>,
37-
}
38-
39-
impl ReadHandler {
40-
pub(crate) fn new(
41-
status: api::Status,
42-
redis_pool: RedisPool,
43-
sensor_specs: sensors::SafeSensorSpecs,
44-
status_modifiers: Vec<Box<dyn modifiers::StatusModifier>>,
45-
) -> ReadHandler {
46-
ReadHandler {
47-
status,
48-
redis_pool,
49-
sensor_specs,
50-
status_modifiers,
51-
}
52-
}
53-
54-
fn build_response_json(&self) -> String {
55-
// Create a mutable copy of the status struct
56-
let mut status_copy = self.status.clone();
57-
58-
// Process registered sensors
59-
for sensor_spec in self.sensor_specs.iter() {
60-
match sensor_spec.get_sensor_value(&self.redis_pool) {
61-
// Value could be read successfullly
62-
Ok(value) => {
63-
if status_copy.sensors.is_none() {
64-
status_copy.sensors = Some(api::Sensors {
65-
people_now_present: vec![],
66-
temperature: vec![],
67-
});
68-
}
69-
sensor_spec
70-
.template
71-
.to_sensor(&value, &mut status_copy.sensors.as_mut().unwrap());
36+
pub async fn json_response_handler(req: Request<Body>) -> Result<Response<Body>, Infallible> {
37+
// Create a mutable copy of the status struct
38+
let state = req.data::<SpaceapiServer>().unwrap();
39+
let mut status_copy = state.status.clone();
40+
41+
// Process registered sensors
42+
for sensor_spec in state.sensor_specs.iter() {
43+
match sensor_spec.get_sensor_value(&state.redis_pool) {
44+
// Value could be read successfullly
45+
Ok(value) => {
46+
if status_copy.sensors.is_none() {
47+
status_copy.sensors = Some(api::Sensors {
48+
people_now_present: vec![],
49+
temperature: vec![],
50+
});
7251
}
52+
sensor_spec
53+
.template
54+
.to_sensor(&value, &mut status_copy.sensors.as_mut().unwrap());
55+
}
7356

74-
// Value could not be read, do error logging
75-
Err(err) => {
76-
warn!(
77-
"Could not retrieve key '{}' from Redis, omiting the sensor",
78-
&sensor_spec.data_key
57+
// Value could not be read, do error logging
58+
Err(err) => {
59+
warn!(
60+
"Could not retrieve key '{}' from Redis, omiting the sensor",
61+
&sensor_spec.data_key
7962
);
80-
match err {
81-
sensors::SensorError::Redis(e) => debug!("Error: {:?}", e),
82-
sensors::SensorError::R2d2(e) => debug!("Error: {:?}", e),
83-
sensors::SensorError::UnknownSensor(e) => warn!("Error: {:?}", e),
84-
}
63+
match err {
64+
sensors::SensorError::Redis(e) => debug!("Error: {:?}", e),
65+
sensors::SensorError::R2d2(e) => debug!("Error: {:?}", e),
66+
sensors::SensorError::UnknownSensor(e) => warn!("Error: {:?}", e),
8567
}
8668
}
8769
}
70+
}
8871

89-
for status_modifier in &self.status_modifiers {
90-
status_modifier.modify(&mut status_copy);
91-
}
72+
for status_modifier in &state.status_modifiers {
73+
status_modifier.modify(&mut status_copy);
74+
}
9275

93-
// Serialize to JSON
94-
serde_json::to_string(&status_copy).expect(
95-
"Status object could not be serialized to JSON. \
76+
// Serialize to JSON
77+
Ok(Response::new(Body::from(serde_json::to_string(&status_copy).expect(
78+
"Status object could not be serialized to JSON. \
9679
Please open an issue at https://github.com/spaceapi-community/spaceapi-server-rs/issues",
97-
)
98-
}
80+
))))
9981
}
10082

10183
/*

src/server/mod.rs

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
//! The SpaceAPI server struct.
22
3+
use std::convert::Infallible;
4+
use std::error::Error;
35
use std::net::ToSocketAddrs;
46
use std::sync::Arc;
57
use std::time::Duration;
6-
use std::convert::Infallible;
7-
use std::error::Error;
88

99
// use iron::Iron;
10+
use hyper::{Body, Request, Response, Server};
1011
use log::debug;
1112
use redis::{ConnectionInfo, IntoConnectionInfo};
12-
use hyper::{Body, Request, Response, Server};
1313
use routerify::{Router, RouterService};
1414

1515
use serde_json::map::Map;
@@ -176,18 +176,11 @@ impl SpaceapiServer {
176176
/// Create and return a Router instance.
177177
fn route(self) -> Router<Body, Infallible> {
178178
Router::builder()
179-
/*
180-
.get( "/", handlers::ReadHandler::new(
181-
self.status.clone(),
182-
self.redis_pool.clone(),
183-
self.sensor_specs.clone(),
184-
self.status_modifiers,
185-
)
186-
)
187-
*/
179+
.data(self)
180+
.get("/", handlers::json_response_handler)
188181
.build()
189182
.unwrap()
190-
/*
183+
/*
191184
.put(
192185
"/sensors/:sensor/",
193186
handlers::UpdateHandler::new(self.redis_pool.clone(), self.sensor_specs),

0 commit comments

Comments
 (0)