-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_receiver.py
More file actions
66 lines (52 loc) · 1.8 KB
/
Copy pathpython_receiver.py
File metadata and controls
66 lines (52 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from flask import Blueprint, request, jsonify
from repositories import next_slot_for_today, save_reading
from calibration import OUT_OF_SOIL_RAW, raw_to_pct
receiver_bp = Blueprint("receiver", __name__)
@receiver_bp.route("/sensor_data", methods=["POST"])
def receive_soil():
data = request.get_json(silent=True) or {}
bed_id = data.get("bed")
sensor_id = data.get("sensor")
moisture = data.get("moisture")
# --- validation ---
if bed_id is None or sensor_id is None or moisture is None:
return jsonify({
"status": "error",
"error": "Missing bed, sensor or moisture"
}), 400
try:
moisture = int(moisture)
except (TypeError, ValueError):
return jsonify({
"status": "error",
"error": "moisture must be an integer"
}), 400
# Ignore invalid "air/unplugged" readings
if moisture >= OUT_OF_SOIL_RAW:
print(f"[SENSOR] ignored (out_of_soil) | bed={bed_id} | sensor={sensor_id} | raw={moisture}")
return jsonify({"status": "ignored", "reason": "out_of_soil"}), 202
moisture_pct = raw_to_pct(moisture)
# --- repository calls (DB handled there) ---
slot = next_slot_for_today(bed_id)
if slot is None:
return jsonify({
"status": "error",
"error": "All 6 slots for today are already filled for this bed"
}), 409
save_reading(
bed_id=bed_id,
sensor_id=sensor_id,
slot=slot,
moisture_raw=moisture,
moisture_pct=moisture_pct
)
# --- debug log ---
print(
f"[SENSOR] saved | "
f"bed={bed_id} | "
f"sensor={sensor_id} | "
f"slot={slot} | "
f"moisture={moisture} |"
f" ({moisture_pct}%)"
)
return jsonify({"status": "ok"}), 200