ResourceHub API. Not for production. Get/Post, Json Serialize/Deserialize

This commit is contained in:
SocioCyber
2026-03-03 06:44:24 -07:00
commit 8a4b324832
22 changed files with 2678 additions and 0 deletions

1
ResourceHub/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target

10
ResourceHub/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,10 @@
# Default ignored files
/shelf/
/workspace.xml
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/

11
ResourceHub/.idea/ResourceHub.iml generated Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="EMPTY_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
ResourceHub/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ResourceHub.iml" filepath="$PROJECT_DIR$/.idea/ResourceHub.iml" />
</modules>
</component>
</project>

6
ResourceHub/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

Binary file not shown.

After

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 540 KiB

2151
ResourceHub/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

10
ResourceHub/Cargo.toml Normal file
View File

@@ -0,0 +1,10 @@
[package]
name = "ResourceHub"
version = "0.1.0"
edition = "2024"
[dependencies]
tokio = { version = "1.32.0", features = ["full"] }
redis = { version = "1.0.4", features = ["tokio-comp"] }
rocket = { version = "0.5.1", features = ["json"] }
tinterm = "0.2.0"

View File

@@ -0,0 +1,3 @@
REDIS_PORT=7878
REDIS_PASSWORD=fswerfds

View File

@@ -0,0 +1,15 @@
services:
cache:
image: redis:7.4-alpine
restart: always
ports:
- "${REDIS_PORT}:6379" # port_on_public:port_in_docker_container
command: redis-server --save 20 1 --loglevel warning --requirepass ${REDIS_PASSWORD}
volumes:
- cache:/data
environment:
- REDIS_PASSWORD=${REDIS_PASSWORD} # Optional, if you will use it in the container
- REDIS_PORT=${REDIS_PORT}
volumes:
cache:
driver: local

34
ResourceHub/Database/run.sh Executable file
View File

@@ -0,0 +1,34 @@
#!/bin/bash
# Check if .env file already exists
if [ -f .env ]; then
echo ".env file already exists. Starting Docker Compose..."
else
# Prompt the user for the Redis password
read -p "Set a Redis port: " REDIS_PORT
read -p "Enter your new Redis password: " REDIS_PASSWORD
echo
# Create the .env file and write the password
cat <<EOL > .env
REDIS_PORT=$REDIS_PORT
REDIS_PASSWORD=$REDIS_PASSWORD
EOL
# Inform the user
echo ".env file created"
echo
echo "--------------------------------------------------------------"
echo "Redis Database accesed with URI: http://127.0.0.1:$REDIS_PORT"
echo "Redis password is: $REDIS_PASSWORD"
echo "--------------------------------------------------------------"
fi
# Start Docker Compose
docker-compose up -d
# show docker container
echo
docker ps

1
ResourceHub/Database/stop.sh Executable file
View File

@@ -0,0 +1 @@
docker-compose down

143
ResourceHub/Readme.md Normal file
View File

@@ -0,0 +1,143 @@
# ResourceHUB [API]
> [!NOTE]
> **[DataCollector]** sends [**sensor's data] **like as *PH Level*, *Humidity*, *Temperature*, etc) as ++JSON++ to this **[API]**
> **RESOURCE HUB - means a Public Storage with Sensors Data**
> ![Resource hub](./images/Resource-hub-2.png)
> ```json
> {
> {
> name: "pH sensor",
> value: "5.5",
> unit: "pH" // to measure the acidity or alkalinity of a solution
> },
> {
> name: "DHT22",
> value: "20.7",
> unit: "RH" // Relative Humidity (RH)
> },
> {
> name: "DHT22",
> value: "35.0",
> unit: "Celsius" // or Fahrenheit Temperature of room
> }
> }
> ```
> # Redis database save recevied [sensor-data] into Table Sensor_data[S5-1]
> - **[S5]** - means SECTOR-5,
> - **"-1"** in [S5**-1**] means SECTOR-5-CELL-1
> ### In concept
> - SECTOR-5-CELL-1 can collect data about tomatos
> - SECTOR-5-CELL-2 can collect data about potatos
> > **In future can be added 'resource' journals,.**
> > **a. "how much" system make a 'tomatos', 'gabbages,.' : 10 tomatos/month, 40 gabbeges/month, etc,.)**
> > **b. "n/year"**
> > **c. **
>
> | id | Sector | Cell | sensor_name | value | unit |
> | --- | ------ | ---- | ----------- | ----- | ------- |
> | 1 | 1 | 1 | pH sensor | 5.5 | pH |
> | 2 | 1 | 1 | DHT22 | 20.7 | RH |
> | 3 | 1 | 1 | DHT22 | 35.0 | Celsius |
> | 4 | 1 | 2 | pH sensor | 2.5 | pH |
> | 5 | 1 | 2 | DHT22 | 20.0 | Celsius |
```mermaid
sequenceDiagram
participant [WebUI/Gtk APP]
participant [DataCollector]
participant [ResourceHUB API]
participant Redis Database
[WebUI/Gtk APP]->>[ResourceHUB API]: Get [sensor's data]
[ResourceHUB API]-->>[WebUI/Gtk APP]: Send [sensor's data]
[ResourceHUB API]->>Redis Database: Query to get [sensor's data]
Redis Database-->>[ResourceHUB API]: Results with data
[DataCollector]->>[ResourceHUB API]: Send [sensor's data]
[ResourceHUB API]->>Redis Database: Query to save [sensor's data]
Redis Database-->>[ResourceHUB API]: Results with save object and status saved!
```
```bash
# Instruction how to install and run ResourceHUB server.
# Time to install: 20-45min (in ~ideal scenarios, without troubleshoting)
# + 20min if try to fix troubles
# Step 1.
# (as root, add "sudo" if need use docker as user)
# Install docker
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh
# Install docker-compose
apt update -y
apt install docker-compose -y
```
```bash
# Step 2.
# Run Redis database (docker-compose)
chmod +x ./Database/run.sh && ./Database/run.sh
```
> [!NOTE]
> ```bash
> # To Run Redis database use ./Database/run.sh
> # ./Database/run.sh
>
> # To Stop Redis database use ./Database/stop.sh
> # chmod +x ./Database/run.sh (this command allow exucute a bash script, use only first time)
> # ./Database/stop.sh
> ```
```bash
# Step 3.
# Install rust and cargo (optionaly if you need use Rust Book to install: https://doc.rust-lang.org/book/ch01-01-installation.html)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
```bash
# Step 4.
# Install libraries
cargo install
```
```bash
# Step 5.
# Okey now you have:
# 1. Runned redis database in docker container (./Database/run.sh)
# 2. Intalled rust with cargo
# 3. Intalled project libraries
# Let's Run a server!
cargo run
```
> [!TIP]
> Don't worry about errors, troubleshooting, etc, make git issue and then i try add new instructions, how to avoid and fix this.
> [!NOTE]
> ```bash
> # get data
> curl -v http://127.0.0.1:8000/api/v1/sensors/data
> ```
> ```bash
> .... # headers
> {"id":1,"name":"Sensor name","value":4.5,"unit":"C"} # <-- Json object with sensor data (in this example you see only one sensor)
> ```
> [!NOTE]
> **DATA COLLECTOR - means a mini PC or Micro-controller with connected sensors, get data from all connected sensors and sends data in json format**
> **to web server, likes RESOURCE HUB [REST API]**
>
> [**DataCollector**]
> **Arduino->[USB]->OrangePiPC->Wifi/Eth - - -> [ResourceHUB API]**
>
> **In my system now i use "arduino nano with DHT22 and pH sensor" connected to Orange Pi PC, arduino sends all data from sensors to Orange Pi PC**
> **Arduino nano connected by usb and use UART - serial port to send data to minipc, and then**
> **Orange Pi PC use wifi/ethernet to sends getted data to web server (To our RESOURCE HUB API)**
>
> **[DataCollector]** sends a **Post** **requests**
> **json** - - **- > **http:123.123.123/api/v1/sensor/data
>
> **[ResourceHUB] **save this data in redis dababase

Binary file not shown.

After

Width:  |  Height:  |  Size: 540 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

View File

@@ -0,0 +1,71 @@
// use database
use rocket::serde::{Deserialize, Serialize, json::Json};
use rocket::response::status;
use rocket::{get, post};
#[derive(Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
pub struct SensorData {
id: Option<u32>,
name: String,
value: f32,
unit: String,
}
// get data json obj
// database.getSensorData()
// send 200 http response with json obj
// 500
// create data json obj
// database.create(obj)
// send 200 http response with json obj
// 500
#[post("/sensors/data", format="json", data="<json>")]
pub async fn create(json: Json<SensorData>) -> status::Accepted<Json<SensorData>> {
let received_data = json.into_inner();
let data = SensorData {
id: None,
name: String::from(received_data.name),
value: received_data.value,
unit: received_data.unit
};
status::Accepted(Json(data))
// saved_data = database.create(data);
// status::Accepted(Json(saved_data))
}
#[get("/sensors/data")]
pub async fn get() -> status::Accepted<Json<SensorData>> {
// get all data from DB
let data = SensorData {
id: Some(1),
name: String::from("Sensor name"),
value: 4.5,
unit: String::from("C")
};
status::Accepted(Json(data))
}
#[get("/sensors/data/<id>")]
pub async fn get_by_id(id: u32) -> status::Accepted<Json<SensorData>> {
// Vulnirability: danger if ID in sql requsets
// http://127.0.0.1:8000/api/v1/sensors/data/?query=SELECT%20id%20FROM%20sensors
// get data from DB
let data: SensorData = SensorData {
id: Some(id),
name: String::from("Sensor name"),
value: 4.5,
unit: String::from("PH")
};
status::Accepted(Json(data))
}

72
ResourceHub/src/main.rs Normal file
View File

@@ -0,0 +1,72 @@
use rocket::{routes};
use crate::util::constants;
mod util {
pub mod constants;
pub mod colored_text;
}
mod endpoints {
pub mod sensors {
pub mod data;
}
}
fn print_debug_info() {
util::colored_text::print_colored_text_info(&format!("- SERVER INFO:"));
util::colored_text::print_colored_text_info(&format!(" - API VERSION: {} ", constants::API_VERSION));
util::colored_text::print_colored_text_info(&format!(" - DB NAME: {} ", constants::DB_NAME));
}
#[rocket::main]
async fn main() -> Result<(), rocket::Error> {
util::colored_text::print_colored_text_brand("> SocioCybereeng ");
util::colored_text::print_colored_text_project("> Project: Hydroponic Systems ");
util::colored_text::print_colored_text_info("- [Welcome to ResourceHUB API] ");
if util::constants::IS_DEBUG == true {
print_debug_info();
}
// let mut status = ServerStatus::Online;
// // Use the colored printing function based on the server status
// match status {
// ServerStatus::Online => {
// }
// ServerStatus::Offline => {
// util::colored_text::print_colored_text_notify("[SERVER_STATUS] The server is stopped.");
// }
// ServerStatus::Starting => {
// util::colored_text::print_colored_text_notify("[SERVER_STATUS] The server is starting.");
// }
// ServerStatus::Stopping => {
// util::colored_text::print_colored_text_notify("[SERVER_STATUS] The server is stopping.");
// }
// ServerStatus::Error(ref err) => {
// util::colored_text::print_colored_text_err(&format!("[SERVER_STATUS] An error occurred: {}", err));
// }
// }
// Start server
let _rocket = rocket::build()
.mount(format!("/api/v{}/", constants::API_VERSION), routes![
endpoints::sensors::data::create,
endpoints::sensors::data::get,
endpoints::sensors::data::get_by_id,
])
.launch()
.await?;
Ok(())
}
// #[macro_use] extern crate rocket;
// #[launch]
// fn rocket() -> _ {
// Create an instance of ServerStatus

View File

View File

@@ -0,0 +1,94 @@
// DBconnector
mod DBconnector {
use redis::AsyncCommands;
async fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1:7878") {
Ok(client) => {
match client.get_multiplexed_async_connection().await {
Ok(conn) => conn,
Err(e) => {
println!("Failed to connect to Redis: {e}");
return;
}
}
},
Err(e) => {
println!("Failed to create Redis client: {e}");
return;
}
};
if let Ok(res) = r.set("foo", "bar").await {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("Error setting foo");
}
match r.get("foo").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bar
},
Err(e) => {
println!("Error getting foo: {e}");
return;
}
};
let hash_fields = [
("model", "Deimos"),
("brand", "Ergonom"),
("type", "Enduro bikes"),
("price", "4972"),
];
if let Ok(res) = r.hset_multiple("bike:1", &hash_fields).await {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("Error setting bike:1");
}
match r.hget("bike:1", "model").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("Error getting bike:1 model: {e}");
return;
}
}
match r.hget("bike:1", "price").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> 4972
},
Err(e) => {
println!("Error getting bike:1 price: {e}");
return;
}
}
match r.hgetall("bike:1").await {
Ok(res) => {
let res: Vec<(String, String)> = res;
for (key, value) in res {
println!("{key}: {value}");
}
// >>> model: Deimos
// >>> brand: Ergonom
// >>> type: Enduro bikes
// >>> price: 4972
},
Err(e) => {
println!("Error getting bike:1: {e}");
return;
}
}
}
}

View File

@@ -0,0 +1,43 @@
use tinterm::*;
pub fn print_colored_text_info(string: &str) {
println!("{}", string
.gradient(Color::LIGHT_CYAN, Color::LIME_GREEN, None)
.bg(Color::BLACK));
}
// pub fn print_colored_text_notify(string: &str) {
// println!("{}", string
// .color(Color::LIGHT_GREEN)
// .bg(Color::BLACK)
// );
// }
// pub fn print_colored_text_err(string: &str) {
// println!("{}", string
// .color(Color::RED)
// .bg(Color::BLACK)
// );
// }
pub fn print_colored_text_brand(string: &str) {
println!("{}", string
.gradient(Color::LIGHT_CYAN, Color::DEEP_SKY_BLUE, None)
.bg(Color::BLACK));
}
// pub fn show_progress(percent: usize) {
// let filled = "█".repeat(percent / 5);
// let empty = "░".repeat(20 - percent / 5);
//
// println!("Progress: [{}{}] {}%",
// filled.color(Color::LIGHT_CYAN),
// empty.color(Color::DARK_GRAY),
// percent
// );
// }
pub fn print_colored_text_project(string: &str) {
println!("{}", string
.gradient(Color::LIGHT_CYAN, Color::CHARTREUSE, None)
.bg(Color::BLACK));
}

View File

@@ -0,0 +1,5 @@
pub const IS_DEBUG: bool = true; // set to 'false' in production!
pub const API_VERSION: &str = "1";
pub const DB_NAME: &str = "Redis";
pub const DB_URL: &str = "redis://127.0.0.1:7878";