Compare commits

..

No commits in common. "5b0f9013aab02296ed3bbc54504ea6785e1b322b" and "e96af3ac7e06ad650e63640bacc9c6c19bcc5a0a" have entirely different histories.

12 changed files with 187 additions and 128 deletions

View File

@ -12,6 +12,10 @@ jobs:
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Set version in Cargo.toml
run: |
VERSION=$(cat VERSION)
sed -i "s/^version = \"__VERSION__\"/version = \"$VERSION\"/" Cargo.toml
- name: Build image with Podman - name: Build image with Podman
env: env:
BUILDAH_ISOLATION: chroot BUILDAH_ISOLATION: chroot

View File

@ -1,6 +1,5 @@
#!/bin/bash #!/bin/bash
set -e
# Patch Cargo.toml version from VERSION file before build # Patch Cargo.toml version from VERSION file before build
VERSION=$(cat VERSION) VERSION=$(cat VERSION)
sed -i 's/^version = ".*"/version = "'"$VERSION"'"/' Cargo.toml sed -i "s/^version = ".*"/version = \"$VERSION\"/" Cargo.toml
exec cargo build exec cargo build

View File

@ -1,3 +0,0 @@
#!/bin/bash
set -e
sed -i 's/^version = ".*"/version = "__VERSION__"/' Cargo.toml

View File

@ -1,12 +0,0 @@
#!/bin/bash
set -e
reset_version() {
sed -i 's/^version = ".*"/version = "__VERSION__"/' Cargo.toml
}
trap reset_version EXIT
VERSION=$(cat VERSION)
sed -i 's/^version = ".*"/version = "'"$VERSION"'"/' Cargo.toml
cargo run

3
.vscode/launch.json vendored
View File

@ -9,8 +9,7 @@
"args": [], "args": [],
"cwd": "${workspaceFolder}", "cwd": "${workspaceFolder}",
"sourceLanguages": ["rust"], "sourceLanguages": ["rust"],
"preLaunchTask": "cargo build", "preLaunchTask": "cargo build"
"postDebugTask": "cargo reset version placeholder"
} }
] ]
} }

14
.vscode/tasks.json vendored
View File

@ -9,19 +9,7 @@
"kind": "build", "kind": "build",
"isDefault": true "isDefault": true
}, },
"problemMatcher": ["$codelldb-rustc"] "problemMatcher": ["$rustc"]
},
{
"label": "cargo reset version placeholder",
"type": "shell",
"command": "bash .vscode/cargo-reset-version.sh",
"problemMatcher": []
},
{
"label": "cargo run",
"type": "shell",
"command": "bash .vscode/cargo-run-version.sh",
"problemMatcher": ["$codelldb-rustc"]
} }
] ]
} }

View File

@ -6,14 +6,11 @@ WORKDIR /usr/src/app
COPY Cargo.toml ./ COPY Cargo.toml ./
COPY Cargo.lock ./ COPY Cargo.lock ./
COPY VERSION ./
COPY src ./src COPY src ./src
COPY templates ./templates COPY templates ./templates
COPY static ./static COPY static ./static
RUN VERSION=$(cat VERSION) \ RUN cargo build --release
&& sed -i 's/^version = "__VERSION__"/version = "'"$VERSION"'"/' Cargo.toml \
&& cargo build --release
# Runtime Stage # Runtime Stage
FROM debian:bookworm-slim FROM debian:bookworm-slim

187
README.md
View File

@ -1,103 +1,190 @@
# Paramod # Tabellen Webserver
Rust-Webserver zur Anzeige und Bearbeitung von Modbus-Tabellen mit Persistierung in `paramod.yaml`. Ein einfacher Rust-Webserver, der eine editierbare 3x3-Tabelle bereitstellt und in einer JSON-Konfigurationsdatei persistiert.
## Projektstruktur
```
paramod/
├── src/
│ └── main.rs
├── templates/
│ ├── index.html
│ └── settings.html
├── static/
│ ├── style.css
│ ├── script.js
│ └── settings.js
├── Cargo.toml
├── Dockerfile
├── .gitignore
└── README.md
```
## Funktionen ## Funktionen
- Tabellen für `modbus_input_register`, `modbus_holding_register` und `modbus_coils` - **3 separate Tabellen** für verschiedene Sensor-Gruppen
- Web-UI zum Bearbeiten und Speichern der Tabellen - **Navigation** mit aktivem Status-Indikator
- Einstellungsseite für `default`, `modbus`, `mqtt` und `influxdb` - **Header mit Logo** für professionelles Erscheinungsbild
- MQTT/Influx-Integration gemäß Konfiguration - **Zeilen hinzufügen/löschen** dynamisch zur Laufzeit
- Speicherung aller Änderungen in `paramod.yaml` - **Einstellungsseite** für MQTT und InfluxDB Konfiguration
- Editierbare Textfelder (Bezeichnung, Adresse, Type, Faktor)
- Toggle-Schalter für Boolean-Werte (MQTT, InfluxDB)
- **Zentrale JSON-Persistierung** für alle Tabellen und Einstellungen
- REST-API für Daten-Management
- Docker-Unterstützung
- Responsive Design
## Lokale Entwicklung ## Lokale Entwicklung
### Voraussetzungen ### Voraussetzungen
- Rust + Cargo - Rust (Version 1.75 oder höher)
- Cargo
### Start ### Installation und Start
```bash ```bash
# Projekt erstellen
cargo new paramod
cd paramod
# Dependencies installieren und starten
cargo run cargo run
``` ```
Server: `http://localhost:8080` Der Server läuft dann auf `http://localhost:8080`
## Docker (Podman) ## Docker
### Image bauen ### Container bauen
```bash ```bash
podman build -t paramod:latest . podman build -t paramod .
``` ```
### Container starten ### Container starten
```bash ```bash
podman run --rm -p 8080:8080 -v "$(pwd)/paramod.yaml:/app/paramod.yaml" paramod:latest poddman run -p 8080:8080 -v $(pwd)/data:/app/data paramod
``` ```
Mit Volume-Mount bleibt die Konfigurationsdatei auch nach Container-Neustarts erhalten.
## Verwendung
1. Öffne `http://localhost:8080` im Browser
2. Navigiere zwischen den Tabellen über das Menü:
- **Tabelle 1, 2, 3**: Verschiedene Sensor-Gruppen
- **⚙️ Einstellungen**: MQTT und InfluxDB Konfiguration
3. In den Tabellen:
- ** Zeile hinzufügen**: Neue Sensor-Einträge erstellen
- **🗑️ Löschen**: Einzelne Zeilen entfernen
- **Felder bearbeiten**:
- Bezeichnung: Name des Sensors
- Adresse: IP-Adresse oder Identifier
- Type: Sensor-Typ (z.B. Temperatur, Luftfeuchtigkeit)
- Faktor: Numerischer Korrekturfaktor
- MQTT: Toggle-Schalter für MQTT-Aktivierung
- InfluxDB: Toggle-Schalter für InfluxDB-Aktivierung
4. **💾 Speichern**: Änderungen persistieren
5. Alle Daten werden zentral in `paramod.yaml` gespeichert
## API Endpoints ## API Endpoints
- `GET /` - `GET /` - Zeigt Tabelle 1
- `GET /table/modbus_input_register` - `GET /table/table2` - Zeigt Tabelle 2
- `GET /table/modbus_holding_register` - `GET /table/table3` - Zeigt Tabelle 3
- `GET /table/modbus_coils` - `GET /settings` - Zeigt Einstellungsseite
- `GET /settings` - `POST /api/save` - Speichert eine Tabelle
- `GET /api/config` - `POST /api/save-settings` - Speichert die Einstellungen
- `POST /api/save` - `GET /static/*` - Statische Dateien (CSS, JS)
- `POST /api/save-settings`
## API-Beispiel: Tabelle speichern ### Beispiel API-Request (Tabelle speichern)
Beispiel für Holding-Register:
```bash ```bash
curl -X POST http://localhost:8080/api/save \ curl -X POST http://localhost:8080/api/save \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{ -d '{
"table_id": "modbus_holding_register", "table_id": "table1",
"rows": [ "rows": [
{ {
"TVsoll": { "bezeichnung": "Sensor 1",
"addr": 2, "adresse": "192.168.1.100",
"type": "INT16", "type": "Temperatur",
"factor": 0.1, "faktor": "1.0",
"write": true,
"mqtt": true, "mqtt": true,
"influxdb": true, "influxdb": false
"comment": "Vorlauf Soll"
}
} }
] ]
}' }'
``` ```
Beispiel für Coils: ### Beispiel API-Request (Einstellungen speichern)
```bash ```bash
curl -X POST http://localhost:8080/api/save \ curl -X POST http://localhost:8080/api/save-settings \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{ -d '{
"table_id": "modbus_coils", "mqtt_broker": "localhost",
"rows": [ "mqtt_port": "1883",
{ "influxdb_url": "http://localhost:8086",
"MgtSystem": { "influxdb_token": "your-token-here"
"addr": 0,
"write": true,
"mqtt": true,
"influxdb": false,
"comment": "Leitsystem aktiv"
}
}
]
}' }'
``` ```
## Konfiguration ## Konfigurationsdatei
Die komplette Konfiguration liegt in `paramod.yaml`. Die komplette Anwendungskonfiguration wird in `table_config.json` gespeichert:
```json
{
"table1": [
{
"bezeichnung": "Temp Sensor 1",
"adresse": "192.168.1.100",
"type": "Temperatur",
"faktor": "1.0",
"mqtt": true,
"influxdb": false
},
{
"bezeichnung": "Temp Sensor 2",
"adresse": "192.168.1.101",
"type": "Temperatur",
"faktor": "1.0",
"mqtt": false,
"influxdb": true
}
],
"table2": [
{
"bezeichnung": "Humidity Sensor 1",
"adresse": "192.168.1.200",
"type": "Luftfeuchtigkeit",
"faktor": "0.5",
"mqtt": true,
"influxdb": true
}
],
"table3": [
{
"bezeichnung": "Pressure Sensor 1",
"adresse": "192.168.1.300",
"type": "Druck",
"faktor": "2.0",
"mqtt": true,
"influxdb": false
}
],
"settings": {
"mqtt_broker": "localhost",
"mqtt_port": "1883",
"influxdb_url": "http://localhost:8086",
"influxdb_token": ""
}
}
```
## Lizenz ## Lizenz

View File

@ -8,7 +8,6 @@ mqtt:
password: 97sm3pHNSMZ4M5qUj0x8 password: 97sm3pHNSMZ4M5qUj0x8
path: heizung/paradigma path: heizung/paradigma
leitsystem_path: heizung/leitsystem2 leitsystem_path: heizung/leitsystem2
set_write_interval_ms: 2000
influxdb: influxdb:
bucket: Paradigma bucket: Paradigma
org: skaville org: skaville

View File

@ -16,10 +16,6 @@ use crate::config::{AppConfig, ModbusValueMaps};
use crate::modbus_types::{ModbusInputRegisterConfig, ModbusHoldingRegisterConfig, ModbusCoilsConfig}; use crate::modbus_types::{ModbusInputRegisterConfig, ModbusHoldingRegisterConfig, ModbusCoilsConfig};
use crate::app_state::AppState; use crate::app_state::AppState;
fn get_config_path() -> String {
std::env::var("CONFIG_PATH").unwrap_or_else(|_| "paramod.yaml".to_string())
}
async fn index(data: web::Data<AppState>) -> Result<HttpResponse> { async fn index(data: web::Data<AppState>) -> Result<HttpResponse> {
let config = data.config.lock().unwrap(); let config = data.config.lock().unwrap();
let value_maps = data.value_maps.lock().unwrap(); let value_maps = data.value_maps.lock().unwrap();
@ -131,10 +127,18 @@ async fn settings_page(data: web::Data<AppState>) -> Result<HttpResponse> {
#[derive(Serialize, Deserialize, Clone)]
#[serde(untagged)]
enum SaveTableRows {
InputRegister(Vec<HashMap<String, ModbusInputRegisterConfig>>),
HoldingRegister(Vec<HashMap<String, ModbusHoldingRegisterConfig>>),
Coils(Vec<HashMap<String, ModbusCoilsConfig>>),
}
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct SaveTableRequest { struct SaveTableRequest {
table_id: String, table_id: String,
rows: serde_json::Value, rows: SaveTableRows,
} }
async fn save_table( async fn save_table(
@ -142,31 +146,28 @@ async fn save_table(
req: web::Json<SaveTableRequest>, req: web::Json<SaveTableRequest>,
) -> Result<HttpResponse> { ) -> Result<HttpResponse> {
let mut config = data.config.lock().unwrap(); let mut config = data.config.lock().unwrap();
let conf_path = get_config_path(); let conf_path = "paramod.yaml";
match req.table_id.as_str() { match req.table_id.as_str() {
"modbus_input_register" => { "modbus_input_register" => {
let rows: Vec<HashMap<String, ModbusInputRegisterConfig>> = if let SaveTableRows::InputRegister(rows) = req.rows.clone() {
match serde_json::from_value(req.rows.clone()) {
Ok(v) => v,
Err(e) => return Ok(HttpResponse::BadRequest().body(format!("Falscher Typ für input_register: {}", e))),
};
config.modbus_input_register = Some(rows); config.modbus_input_register = Some(rows);
} else {
return Ok(HttpResponse::BadRequest().body("Falscher Typ für input_register"));
}
} }
"modbus_holding_register" => { "modbus_holding_register" => {
let rows: Vec<HashMap<String, ModbusHoldingRegisterConfig>> = if let SaveTableRows::HoldingRegister(rows) = req.rows.clone() {
match serde_json::from_value(req.rows.clone()) {
Ok(v) => v,
Err(e) => return Ok(HttpResponse::BadRequest().body(format!("Falscher Typ für holding_register: {}", e))),
};
config.modbus_holding_register = Some(rows); config.modbus_holding_register = Some(rows);
} else {
return Ok(HttpResponse::BadRequest().body("Falscher Typ für holding_register"));
}
} }
"modbus_coils" => { "modbus_coils" => {
let rows: Vec<HashMap<String, ModbusCoilsConfig>> = if let SaveTableRows::Coils(rows) = req.rows.clone() {
match serde_json::from_value(req.rows.clone()) {
Ok(v) => v,
Err(e) => return Ok(HttpResponse::BadRequest().body(format!("Falscher Typ für coils: {}", e))),
};
config.modbus_coils = Some(rows); config.modbus_coils = Some(rows);
} else {
return Ok(HttpResponse::BadRequest().body("Falscher Typ für coils"));
}
} }
_ => return Ok(HttpResponse::BadRequest().body("Invalid table_id")), _ => return Ok(HttpResponse::BadRequest().body("Invalid table_id")),
} }
@ -174,7 +175,7 @@ async fn save_table(
Ok(s) => s, Ok(s) => s,
Err(e) => return Ok(HttpResponse::InternalServerError().body(format!("Serialisierungsfehler: {}", e))), Err(e) => return Ok(HttpResponse::InternalServerError().body(format!("Serialisierungsfehler: {}", e))),
}; };
if let Err(e) = fs::write(&conf_path, yaml_str) { if let Err(e) = fs::write(conf_path, yaml_str) {
return Ok(HttpResponse::InternalServerError().body(format!("Fehler beim Schreiben: {}", e))); return Ok(HttpResponse::InternalServerError().body(format!("Fehler beim Schreiben: {}", e)));
} }
Ok(HttpResponse::Ok().body("success")) Ok(HttpResponse::Ok().body("success"))
@ -199,16 +200,16 @@ async fn save_settings(
// Value-Maps neu initialisieren // Value-Maps neu initialisieren
let mut value_maps = data.value_maps.lock().unwrap(); let mut value_maps = data.value_maps.lock().unwrap();
*value_maps = ModbusValueMaps::from_config(&new_config); *value_maps = ModbusValueMaps::from_config(&new_config);
let conf_path = get_config_path(); let conf_path = "paramod.yaml";
let yaml_str = match serde_yaml::to_string(&new_config) { let yaml_str = match serde_yaml::to_string(&new_config) {
Ok(s) => s, Ok(s) => s,
Err(e) => return Ok(HttpResponse::InternalServerError().body(format!("Serialisierungsfehler: {}", e))), Err(e) => return Ok(HttpResponse::InternalServerError().body(format!("Serialisierungsfehler: {}", e))),
}; };
if let Err(e) = fs::write(&conf_path, yaml_str) { if let Err(e) = fs::write(conf_path, yaml_str) {
return Ok(HttpResponse::InternalServerError().body(format!("Fehler beim Schreiben: {}", e))); return Ok(HttpResponse::InternalServerError().body(format!("Fehler beim Schreiben: {}", e)));
} }
// Reload config from file // Reload config from file
let conf_str = match std::fs::read_to_string(&conf_path) { let conf_str = match std::fs::read_to_string(conf_path) {
Ok(s) => s, Ok(s) => s,
Err(e) => return Ok(HttpResponse::InternalServerError().body(format!("Fehler beim Lesen: {}", e))), Err(e) => return Ok(HttpResponse::InternalServerError().body(format!("Fehler beim Lesen: {}", e))),
}; };
@ -230,8 +231,9 @@ async fn get_config(data: web::Data<AppState>) -> HttpResponse {
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
let config_path = get_config_path();
let app_state = web::Data::new(AppState::load_from_conf(&config_path)); let config_path = "paramod.yaml";
let app_state = web::Data::new(AppState::load_from_conf(config_path));
// Starte Modbus-Polling-Thread // Starte Modbus-Polling-Thread
{ {
@ -243,7 +245,7 @@ async fn main() -> std::io::Result<()> {
&config.modbus_holding_register, &config.modbus_holding_register,
&config.modbus_coils, &config.modbus_coils,
value_maps, value_maps,
std::time::Duration::from_secs(10), // Poll-Intervall std::time::Duration::from_secs(2), // Poll-Intervall
); );
} }

View File

@ -37,7 +37,7 @@ pub fn start_mqtt_thread(config: Arc<Mutex<AppConfig>>, values: Arc<Mutex<Modbus
if let Err(e) = client.subscribe(set_topic, QoS::AtLeastOnce) { if let Err(e) = client.subscribe(set_topic, QoS::AtLeastOnce) {
eprintln!("MQTT Subscribe fehlgeschlagen: {}", e); eprintln!("MQTT Subscribe fehlgeschlagen: {}", e);
} }
let leitsystem_state_topic = format!("{}/active", leitsystem_path.trim_end_matches('/')); let leitsystem_state_topic = format!("{}/state", leitsystem_path.trim_end_matches('/'));
if let Err(e) = client.subscribe(leitsystem_state_topic.clone(), QoS::AtLeastOnce) { if let Err(e) = client.subscribe(leitsystem_state_topic.clone(), QoS::AtLeastOnce) {
eprintln!("MQTT Subscribe Leitsystem fehlgeschlagen: {}", e); eprintln!("MQTT Subscribe Leitsystem fehlgeschlagen: {}", e);
} }

View File

@ -56,7 +56,7 @@ function addRow() {
<button class="delete-btn" onclick="deleteRow(this)">🗑</button> <button class="delete-btn" onclick="deleteRow(this)">🗑</button>
</td> </td>
`; `;
} else if (typeof tableId !== 'undefined' && tableId === 'modbus_holding_register') { } else if (typeof tableId !== 'undefined' && tableId === 'modbus_holding_registers') {
newRow.innerHTML = ` newRow.innerHTML = `
<td><input type='text' class='text-input' data-field='bezeichnung' value='' /></td> <td><input type='text' class='text-input' data-field='bezeichnung' value='' /></td>
<td><input type='text' class='text-input' data-field='adresse' value='' /></td> <td><input type='text' class='text-input' data-field='adresse' value='' /></td>
@ -147,14 +147,14 @@ async function saveTable() {
influxdb: influxdb, influxdb: influxdb,
comment: comment comment: comment
}; };
} else if (typeof tableId !== 'undefined' && tableId === 'modbus_holding_register') { } else if (typeof tableId !== 'undefined' && tableId === 'modbus_holding_registers') {
const write = row.querySelector("input[data-field='write']")?.checked || false; const write = row.querySelector("input[data-field='write']")?.checked || false;
const type = row.querySelector("input[data-field='type']")?.value || null; const rtype = row.querySelector("input[data-field='type']")?.value || null;
const factor = parseFloat(row.querySelector("input[data-field='factor']")?.value || row.querySelector("input[data-field='faktor']")?.value || '1.0'); const factor = parseFloat(row.querySelector("input[data-field='factor']")?.value || row.querySelector("input[data-field='faktor']")?.value || '1.0');
const comment = row.querySelector("input[data-field='comment']")?.value || null; const comment = row.querySelector("input[data-field='comment']")?.value || null;
value = { value = {
addr: addr, addr: addr,
type: type, rtype: rtype,
factor: factor, factor: factor,
write: write, write: write,
mqtt: mqtt, mqtt: mqtt,
@ -162,12 +162,12 @@ async function saveTable() {
comment: comment comment: comment
}; };
} else { } else {
const type = row.querySelector("input[data-field='type']")?.value || null; const rtype = row.querySelector("input[data-field='type']")?.value || null;
const factor = parseFloat(row.querySelector("input[data-field='factor']")?.value || row.querySelector("input[data-field='faktor']")?.value || '1.0'); const factor = parseFloat(row.querySelector("input[data-field='factor']")?.value || row.querySelector("input[data-field='faktor']")?.value || '1.0');
const comment = row.querySelector("input[data-field='comment']")?.value || null; const comment = row.querySelector("input[data-field='comment']")?.value || null;
value = { value = {
addr: addr, addr: addr,
type: type, rtype: rtype,
factor: factor, factor: factor,
mqtt: mqtt, mqtt: mqtt,
influxdb: influxdb, influxdb: influxdb,
@ -196,9 +196,8 @@ async function saveTable() {
messageDiv.className = 'message success'; messageDiv.className = 'message success';
messageDiv.textContent = '✓ Erfolgreich gespeichert!'; messageDiv.textContent = '✓ Erfolgreich gespeichert!';
} else { } else {
const errorText = (await response.text()) || 'Unbekannter Fehler';
messageDiv.className = 'message error'; messageDiv.className = 'message error';
messageDiv.textContent = `✗ Fehler beim Speichern: ${errorText}`; messageDiv.textContent = '✗ Fehler beim Speichern!';
} }
setTimeout(() => { setTimeout(() => {