Fully working plot, server, and sensor with timestamps
This commit is contained in:
26
main.go
26
main.go
@@ -12,20 +12,28 @@ import (
|
||||
)
|
||||
|
||||
var dataFile *os.File
|
||||
var startTime time.Time
|
||||
var berlinTZ *time.Location
|
||||
|
||||
type VoltageData struct {
|
||||
Voltage float64 `json:"voltage"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
berlinTZ, err = time.LoadLocation("Europe/Berlin")
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to load Berlin timezone: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func initDataFile() {
|
||||
// Ensure the data/ directory exists
|
||||
if err := os.MkdirAll("data", os.ModePerm); err != nil {
|
||||
log.Fatalf("Failed to create data directory: %v", err)
|
||||
}
|
||||
|
||||
// Generate a filename with timestamp
|
||||
filename := filepath.Join("data", fmt.Sprintf("voltages_%s.csv", time.Now().Format("20060102_150405")))
|
||||
// Generate a filename with timestamp in Berlin local time
|
||||
filename := filepath.Join("data", fmt.Sprintf("voltages_%s.csv", time.Now().In(berlinTZ).Format("20060102_150405")))
|
||||
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to open data file: %v", err)
|
||||
@@ -35,9 +43,7 @@ func initDataFile() {
|
||||
log.Printf("Logging voltage data to %s\n", filename)
|
||||
|
||||
// Write CSV header
|
||||
_, _ = dataFile.WriteString("time_s,voltage\n")
|
||||
|
||||
startTime = time.Now()
|
||||
_, _ = dataFile.WriteString("timestamp,voltage\n")
|
||||
}
|
||||
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -60,15 +66,15 @@ func handler(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Compute relative time
|
||||
relTime := time.Since(startTime).Seconds()
|
||||
// Get current timestamp in Berlin
|
||||
timestamp := time.Now().In(berlinTZ).Format("2006-01-02 15:04:05.000")
|
||||
|
||||
// Print voltage to console
|
||||
fmt.Printf("Received voltage: %f at time %.3f s\n", v.Voltage, relTime)
|
||||
fmt.Printf("Received voltage: %f at %s\n", v.Voltage, timestamp)
|
||||
|
||||
// Append CSV line to file
|
||||
if dataFile != nil {
|
||||
if _, err := dataFile.WriteString(fmt.Sprintf("%.3f,%.6f\n", relTime, v.Voltage)); err != nil {
|
||||
if _, err := dataFile.WriteString(fmt.Sprintf("%s,%.6f\n", timestamp, v.Voltage)); err != nil {
|
||||
log.Printf("Failed to write to file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
31
plot.py
31
plot.py
@@ -1,7 +1,10 @@
|
||||
import os
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.dates as mdates
|
||||
import numpy as np
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
DATA_DIR = "data"
|
||||
|
||||
# Find the latest data file
|
||||
@@ -13,18 +16,30 @@ latest_file = max(files, key=lambda f: os.path.getmtime(os.path.join(DATA_DIR, f
|
||||
filepath = os.path.join(DATA_DIR, latest_file)
|
||||
print(f"Plotting data from {filepath}")
|
||||
|
||||
# Load CSV data (skip header)
|
||||
data = np.loadtxt(filepath, delimiter=",", skiprows=1)
|
||||
times = data[:, 0]
|
||||
voltages = data[:, 1]
|
||||
# Load CSV data
|
||||
timestamps = []
|
||||
voltages = []
|
||||
|
||||
with open(filepath, "r") as f:
|
||||
next(f) # skip header
|
||||
for line in f:
|
||||
ts_str, v_str = line.strip().split(",")
|
||||
ts = datetime.strptime(ts_str, "%Y-%m-%d %H:%M:%S.%f")
|
||||
timestamps.append(ts)
|
||||
voltages.append(float(v_str))
|
||||
|
||||
# Plot
|
||||
plt.figure(figsize=(10, 5))
|
||||
plt.plot(times, voltages, marker='o', linestyle='-')
|
||||
plt.xlabel("Time (s)")
|
||||
plt.figure(figsize=(12, 5))
|
||||
plt.plot(timestamps, voltages, marker='o', linestyle='-')
|
||||
|
||||
plt.xlabel("Time (CET)")
|
||||
plt.ylabel("Voltage (V)")
|
||||
plt.title(f"Voltage Measurements ({latest_file})")
|
||||
plt.grid(True)
|
||||
|
||||
# Format x-axis for readable time
|
||||
plt.gcf().autofmt_xdate()
|
||||
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user