Telemetry
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import json
|
||||
import os
|
||||
import paho.mqtt.publish as publish
|
||||
import sys
|
||||
|
||||
# Retrieve broker parameters from shared config or environment variables
|
||||
MQTT_HOST = os.getenv("MQTT_HOST", "localhost")
|
||||
MQTT_PORT = int(os.getenv("MQTT_PORT", 8884))
|
||||
MQTT_USER = os.getenv("MQTT_USER", None)
|
||||
MQTT_PASS = os.getenv("MQTT_PASS", None)
|
||||
|
||||
|
||||
def send_command(topic: str = "cmd/all", payload: dict | str = None):
|
||||
"""
|
||||
Publishes an MQTT command payload to a given topic.
|
||||
"""
|
||||
if payload is None:
|
||||
payload = {}
|
||||
|
||||
if isinstance(payload, dict):
|
||||
payload_str = json.dumps(payload)
|
||||
else:
|
||||
payload_str = str(payload)
|
||||
|
||||
auth = None
|
||||
if MQTT_USER:
|
||||
auth = {"username": MQTT_USER, "password": MQTT_PASS or ""}
|
||||
|
||||
publish.single(
|
||||
topic=topic,
|
||||
payload=payload_str,
|
||||
hostname=MQTT_HOST,
|
||||
port=MQTT_PORT,
|
||||
auth=auth
|
||||
)
|
||||
print(f"[MQTT] Published command to '{topic}': {payload_str}")
|
||||
+35
-15
@@ -1,11 +1,14 @@
|
||||
import os
|
||||
import base64
|
||||
import uuid
|
||||
import datetime
|
||||
import sys
|
||||
from flask import Flask, request, jsonify
|
||||
from pymongo import MongoClient
|
||||
from APIs import generate, EdamamAPI
|
||||
import sys
|
||||
from APIs.mqtt import send_command
|
||||
from microwaveCookPlanner import MicrowaveCookPlanner
|
||||
|
||||
sys.path.insert(0, '..')
|
||||
try:
|
||||
from shared import config
|
||||
@@ -18,12 +21,13 @@ app = Flask(__name__)
|
||||
# Configuration & Setup
|
||||
# ---------------------------------------------------------
|
||||
|
||||
# Configure MongoDB connection (adjust the URI as needed for your environment)
|
||||
# Configure MongoDB connection
|
||||
MONGO_URI = os.getenv("MONGO_URI", "mongodb://localhost:27017/")
|
||||
client = MongoClient(MONGO_URI)
|
||||
db = client["microwave_network_db"]
|
||||
|
||||
cooking_collection = db["cooking_parameters"]
|
||||
device_network_collection = db["device_network"]
|
||||
telemetry_collection = db["telemetry_data"]
|
||||
|
||||
# Ensure the camera image storage directory exists when the app starts
|
||||
CAMERA_IMAGE_DIR = "storage/dishCameraImages"
|
||||
@@ -103,29 +107,45 @@ def cooking_params():
|
||||
# 5. Return complete output
|
||||
return jsonify(cook_plan), 201
|
||||
|
||||
@app.route("/device-network", methods=["POST"])
|
||||
def device_network():
|
||||
|
||||
@app.route("/telemetry", methods=["POST"])
|
||||
def telemetry():
|
||||
data = request.get_json()
|
||||
|
||||
if not data:
|
||||
return jsonify({"error": "Invalid or missing JSON payload"}), 400
|
||||
|
||||
# Stamp UTC timestamp for Node-RED queries
|
||||
data["received_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
|
||||
# 2. Save to MongoDB
|
||||
try:
|
||||
# Insert the dictionary directly into Mongo (it will retain your exact JSON keys)
|
||||
device_network_collection.insert_one(data)
|
||||
|
||||
return "", 200
|
||||
# Mongo creates '_id' automatically upon insertion
|
||||
telemetry_collection.insert_one(data)
|
||||
return jsonify({"status": "success", "message": "Telemetry saved"}), 200
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({"error": f"Database error: {str(e)}"}), 500
|
||||
|
||||
|
||||
|
||||
@app.route("/debug", methods=["GET"])
|
||||
def debug():
|
||||
image_path = "microwaveDish.jpg"
|
||||
edamam = EdamamAPI()
|
||||
return edamam.analyze_dish_image(image_path)
|
||||
# Construct external HTTP endpoint dynamically based on incoming request host
|
||||
telemetry_url = f"{request.host_url.rstrip('/')}/telemetry"
|
||||
|
||||
cmd_payload = {
|
||||
"action": "request_telemetry",
|
||||
"endpoint": telemetry_url
|
||||
}
|
||||
|
||||
try:
|
||||
send_command(topic="cmd/all", payload=cmd_payload)
|
||||
return jsonify({
|
||||
"status": "Telemetry command sent to cmd/all",
|
||||
"published_payload": cmd_payload
|
||||
}), 200
|
||||
except Exception as e:
|
||||
return jsonify({"error": f"Failed to publish MQTT command: {str(e)}"}), 500
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=config.DEBUG)
|
||||
app.run(debug=getattr(config, "DEBUG", True))
|
||||
Reference in New Issue
Block a user