Antennas basic endpoints (#4)

Co-authored-by: Felipe Diniello <felipediniello@pm.me>
Reviewed-on: #4
This commit was merged in pull request #4.
This commit is contained in:
2023-07-23 18:53:49 +02:00
parent 990e8955e4
commit c529335eac
16 changed files with 241 additions and 14 deletions

View File

@@ -18,4 +18,5 @@ dotenv = "0.15.0"
chrono = "0.4.24"
paho-mqtt = "0.12.1"
serde = "1.0.162"
serde_json = { version = "1.0.95" }
serde_json = { version = "1.0.95" }
diesel = { version = "2.1.0", features = ["postgres", "extras"] }

View File

@@ -14,6 +14,8 @@ dotenv = { workspace = true }
chrono = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diesel = { workspace = true }
influxdb2 = "0.4.2"
influxdb2-structmap = "0.2"

9
kairo-common/diesel.toml Normal file
View File

@@ -0,0 +1,9 @@
# For documentation on how to configure this file,
# see https://diesel.rs/guides/configuring-diesel-cli
[print_schema]
file = "src/schema.rs"
custom_type_derives = ["diesel::query_builder::QueryId"]
[migrations_directory]
dir = "migrations"

View File

View File

@@ -0,0 +1,6 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
DROP FUNCTION IF EXISTS diesel_set_updated_at();

View File

@@ -0,0 +1,36 @@
-- This file was automatically created by Diesel to setup helper functions
-- and other internal bookkeeping. This file is safe to edit, any future
-- changes will be added to existing projects as new migrations.
-- Sets up a trigger for the given table to automatically set a column called
-- `updated_at` whenever the row is modified (unless `updated_at` was included
-- in the modified columns)
--
-- # Example
--
-- ```sql
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
--
-- SELECT diesel_manage_updated_at('users');
-- ```
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
BEGIN
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
BEGIN
IF (
NEW IS DISTINCT FROM OLD AND
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
) THEN
NEW.updated_at := current_timestamp;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

View File

@@ -0,0 +1,3 @@
-- This file should undo anything in `up.sql`
DROP TABLE antennas;

View File

@@ -0,0 +1,10 @@
-- Your SQL goes here
CREATE TABLE antennas (
id VARCHAR(17) PRIMARY KEY,
tssi DOUBLE PRECISION NOT NULL,
pos_x DOUBLE PRECISION NOT NULL,
pos_y DOUBLE PRECISION NOT NULL,
pos_z DOUBLE PRECISION NOT NULL,
comment TEXT
);

View File

@@ -4,12 +4,12 @@
#![allow(confusable_idents)]
pub mod influx;
pub mod postgres;
// random functions for mqtt
// random functions for mqtt
pub mod mqtt;
pub mod unit_conversion;
// Commonly used types across the services
mod types {
pub mod mac; // deprecated for the time being.
@@ -18,7 +18,8 @@ mod types {
pub type Point = types::point::Point;
pub type MAC = types::mac::MAC;
// DB models: for SQL with Diesel and InfluxDB and influxdb-derive
pub mod schema;
mod models {
pub mod antenna;
pub mod beacon_measure;
@@ -30,8 +31,10 @@ mod models {
pub data: Vec<crate::models::beacon_measure::BeaconMeasure>,
}
}
pub type Antenna = models::antenna::Antenna;
pub type DeviceReport = models::DeviceReport;
pub type Antenna = models::antenna::Antenna;
pub type KnownPosition = models::known_position::KnownPosition;
pub type DynamicDeviceStatus = models::dynamic_device_status::DynamicDeviceStatus;
pub type BeaconMeasure = models::beacon_measure::BeaconMeasure;

View File

@@ -1,15 +1,27 @@
use diesel::prelude::*;
use std::f64::consts::PI;
use crate::{unit_conversion::UnitsConversion, Point};
#[derive(Debug, Clone, Default)]
#[derive(
Debug,
Clone,
Queryable,
Selectable,
Insertable,
AsChangeset,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(check_for_backend(diesel::pg::Pg))]
#[diesel(table_name = crate::schema::antennas)]
pub struct Antenna {
pub id: String,
pub tssi: f64,
pub pos_x: f64,
pub pos_y: f64,
pub pos_z: f64,
pub comment: Option<String>,
pos_x: f64,
pos_y: f64,
pos_z: f64,
}
impl Antenna {

View File

@@ -0,0 +1,25 @@
use diesel::prelude::*;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
pub type DbConn = diesel::pg::PgConnection;
pub type DbPool = Pool<ConnectionManager<PgConnection>>;
pub struct DbPooledConn(pub PooledConnection<ConnectionManager<PgConnection>>);
pub fn establish_connection() -> DbConn {
let database_url = dotenv::var("DATABASE_URL").expect("DATABASE_URL must be set");
PgConnection::establish(&database_url)
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
}
pub fn init_pool() -> DbPool {
let database_url = dotenv::var("DATABASE_URL").expect("DATABASE_URL must be set");
let manager = ConnectionManager::<PgConnection>::new(database_url);
DbPool::new(manager).expect("Error connecting to DB")
}
impl std::ops::Deref for DbPooledConn {
type Target = PgConnection;
fn deref(&self) -> &Self::Target {
&self.0
}
}

View File

@@ -0,0 +1,13 @@
// @generated automatically by Diesel CLI.
diesel::table! {
antennas (id) {
#[max_length = 17]
id -> Varchar,
tssi -> Float8,
pos_x -> Float8,
pos_y -> Float8,
pos_z -> Float8,
comment -> Nullable<Text>,
}
}

View File

@@ -6,3 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
diesel = { workspace = true}
rocket = { version = "0.5.0-rc.3", features = ["json"] }
kairo-common = { path = "../kairo-common" }

View File

@@ -0,0 +1,77 @@
use diesel::prelude::*;
use rocket::{http::Status, serde::json::Json, State};
use kairo_common::{postgres, schema::antennas, Antenna};
#[rocket::get("/id/<id>")]
pub fn get_by_id(db_pool: &State<postgres::DbPool>, id: String) -> Option<Json<Antenna>> {
let mut db = db_pool.get().unwrap();
let res = antennas::table
.select(antennas::all_columns)
.find(id)
.get_result::<Antenna>(&mut db);
match res {
Ok(v) => Some(rocket::serde::json::Json(v)),
_ => None,
}
}
#[rocket::get("/")]
pub fn get_list(db_pool: &State<postgres::DbPool>) -> Json<Vec<Antenna>> {
let mut db = db_pool.get().unwrap();
let res = antennas::table
.select(antennas::all_columns)
.load::<Antenna>(&mut db);
match res {
Ok(v) => rocket::serde::json::Json(v),
_ => rocket::serde::json::Json(vec![]),
}
}
#[rocket::post("/new", format = "json", data = "<antenna>")]
pub fn new(db_pool: &State<postgres::DbPool>, antenna: Json<Antenna>) -> Status {
let mut db = db_pool.get().unwrap();
let res = diesel::insert_into(antennas::table)
.values(antenna.0)
.execute(&mut db);
match res {
Ok(_) => Status::Ok,
_ => Status::NotAcceptable,
}
}
#[rocket::patch("/update", format = "json", data = "<antenna>")]
pub fn update(db_pool: &State<postgres::DbPool>, antenna: Json<Antenna>) -> Status {
let mut db = db_pool.get().unwrap();
let res = diesel::update(antennas::table)
.filter(antennas::id.eq(antenna.id.clone()))
.set(antenna.0)
.execute(&mut db);
match res {
Ok(0) => Status::NotModified,
Ok(1) => Status::Ok,
_ => Status::BadRequest,
}
}
#[rocket::delete("/delete/<id>")]
pub fn delete(db_pool: &State<postgres::DbPool>, id: String) -> Status {
let mut db = db_pool.get().unwrap();
let res = diesel::delete(antennas::table)
.filter( antennas::id.eq(id) )
.execute(&mut db);
match res {
Ok(1) => Status::Ok,
_ => Status::BadRequest,
}
}

View File

@@ -1,3 +1,31 @@
fn main() {
println!("Hello, world!");
#[macro_use]
extern crate rocket;
mod antennas;
use std::path::{Path, PathBuf};
use rocket::fs::NamedFile;
use rocket::response::status::NotFound;
use kairo_common::postgres;
#[get("/<file..>")]
async fn serve_file(file: PathBuf) -> Result<NamedFile, NotFound<String>> {
let path = Path::new("static/").join(file);
NamedFile::open(&path)
.await
.map_err(|e| NotFound(e.to_string()))
}
#[launch]
fn rocket() -> _ {
rocket::build()
.manage(postgres::init_pool())
.mount("/static", routes![serve_file])
.mount("/antennas/", routes![antennas::get_by_id])
.mount("/antennas/", routes![antennas::get_list])
.mount("/antennas/", routes![antennas::delete])
.mount("/antennas/", routes![antennas::update])
.mount("/antennas/", routes![antennas::new])
}

View File

@@ -3,9 +3,7 @@ use futures::stream::StreamExt;
mod handler;
mod position_solver;
use kairo_common::mqtt::for_async::{
get_mqtt_cli_and_stream, mqtt_cli_reconnect, mqtt_subscribe,
};
use kairo_common::mqtt::for_async::{get_mqtt_cli_and_stream, mqtt_cli_reconnect, mqtt_subscribe};
#[tokio::main]
async fn main() {