This commit is contained in:
2026-05-11 03:27:21 +03:30
parent cf7cbb937c
commit d0e68a1a56
854 changed files with 102985 additions and 76 deletions
+14
View File
@@ -0,0 +1,14 @@
API_TARGET_URL = "http://backend-web:8000"
API_KEY = "12345"
REQUEST_INTERVAL_SECONDS = 10
STATIC_SENSOR_PAYLOAD = {
"uuid": "11111111111111111111",
"soil_moisture": 42.5,
"soil_temperature": 24.3,
"soil_ph": 6.8,
"soil_ec": 1.4,
"nitrogen": 32,
"phosphorus": 18,
"potassium": 27,
}
@@ -0,0 +1,72 @@
import json
import time
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from django.core.management.base import BaseCommand
from ingest.constants import API_KEY, API_TARGET_URL, REQUEST_INTERVAL_SECONDS, STATIC_SENSOR_PAYLOAD
class Command(BaseCommand):
help = "Send the static soil sensor payload to the upstream API every 10 seconds."
def add_arguments(self, parser):
parser.add_argument(
"--once",
action="store_true",
help="Send the request once and exit.",
)
def handle(self, *args, **options):
run_once = options["once"]
self.stdout.write(
self.style.SUCCESS(
f"Starting sensor sender -> {API_TARGET_URL} (interval: {REQUEST_INTERVAL_SECONDS}s)"
)
)
while True:
self.send_payload()
if run_once:
break
time.sleep(REQUEST_INTERVAL_SECONDS)
def send_payload(self):
body = json.dumps(STATIC_SENSOR_PAYLOAD).encode("utf-8")
request = Request(
API_TARGET_URL,
data=body,
headers={
"Content-Type": "application/json",
"api_key": API_KEY,
},
method="POST",
)
try:
with urlopen(request, timeout=15) as response:
response_body = response.read().decode("utf-8", errors="replace")
self.stdout.write(
self.style.SUCCESS(
f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Sent payload successfully - status {response.status}"
)
)
if response_body:
self.stdout.write(response_body)
except HTTPError as exc:
error_body = exc.read().decode("utf-8", errors="replace")
self.stderr.write(
self.style.ERROR(
f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Upstream error - status {exc.code}"
)
)
if error_body:
self.stderr.write(error_body)
except URLError as exc:
self.stderr.write(
self.style.ERROR(
f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Connection error - {exc.reason}"
)
)
@@ -0,0 +1,166 @@
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>شبیه ساز سنسور خاک</title>
<style>
:root {
--bg: linear-gradient(135deg, #f4efe6 0%, #dce8d5 100%);
--card: rgba(255, 252, 246, 0.92);
--ink: #203126;
--muted: #5a6b60;
--accent: #2f6a4f;
--accent-dark: #1e4936;
--border: rgba(47, 106, 79, 0.18);
--shadow: 0 24px 60px rgba(32, 49, 38, 0.16);
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
font-family: Tahoma, sans-serif;
background: var(--bg);
color: var(--ink);
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
}
.shell {
width: min(980px, 100%);
background: var(--card);
border: 1px solid var(--border);
border-radius: 28px;
box-shadow: var(--shadow);
overflow: hidden;
}
.hero {
padding: 32px;
background: linear-gradient(135deg, rgba(47,106,79,.95), rgba(85,130,96,.88));
color: #f9f6ee;
}
.hero h1 { margin: 0 0 12px; font-size: clamp(28px, 5vw, 42px); }
.hero p { margin: 0; line-height: 1.8; max-width: 700px; }
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 24px;
padding: 24px;
}
.panel {
border: 1px solid var(--border);
border-radius: 22px;
padding: 20px;
background: rgba(255,255,255,.68);
}
label {
display: block;
font-weight: bold;
margin-bottom: 8px;
}
input, textarea {
width: 100%;
border: 1px solid rgba(32,49,38,.14);
border-radius: 14px;
padding: 12px 14px;
font: inherit;
background: rgba(255,255,255,.9);
color: var(--ink);
}
textarea { min-height: 320px; resize: vertical; direction: ltr; text-align: left; }
.hint {
color: var(--muted);
font-size: 14px;
margin-top: 8px;
line-height: 1.8;
}
button {
border: 0;
background: var(--accent);
color: #fff;
padding: 14px 18px;
border-radius: 14px;
font: inherit;
cursor: pointer;
min-width: 180px;
}
button:hover { background: var(--accent-dark); }
pre {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
background: #18241c;
color: #d9f4e2;
border-radius: 18px;
padding: 16px;
min-height: 220px;
direction: ltr;
text-align: left;
}
</style>
</head>
<body>
<main class="shell">
<section class="hero">
<h1>ارسال استاتیک داده سنسور خاک</h1>
<p>
این صفحه بدون هیچ اتصال به دیتابیس، یک payload استاتیک از داده های سنسور خاک را با متد POST
و هدر <code>api_key</code> به API مقصد ارسال می کند.
</p>
</section>
<section class="grid">
<form class="panel" id="sender-form">
<label for="target_url">آدرس API مقصد</label>
<input id="target_url" name="target_url" value="{{ default_url }}" required>
<label for="api_key" style="margin-top: 16px;">API Key</label>
<input id="api_key" name="api_key" value="{{ default_api_key }}" required>
<label for="payload" style="margin-top: 16px;">JSON ارسالی</label>
<textarea id="payload" readonly>{{ default_payload }}</textarea>
<p class="hint">
فیلدها شامل uuid، رطوبت خاک، دمای خاک، pH، EC، نیتروژن، فسفر و پتاسیم هستند و فعلا همه به صورت استاتیک تعریف شده اند.
</p>
<div style="margin-top: 18px; display: flex; gap: 12px; flex-wrap: wrap;">
<button type="submit">ارسال به API</button>
</div>
</form>
<section class="panel">
<label>نتیجه درخواست</label>
<pre id="result">هنوز درخواستی ارسال نشده است.</pre>
<p class="hint">
در پاسخ، payload ارسالی، هدرهای ارسال شده و پاسخ API مقصد نمایش داده می شود.
</p>
</section>
</section>
</main>
<script>
const form = document.getElementById('sender-form');
const result = document.getElementById('result');
form.addEventListener('submit', async (event) => {
event.preventDefault();
result.textContent = 'در حال ارسال...';
const formData = new FormData(form);
try {
const response = await fetch('/api/ingest/forward/', {
method: 'POST',
body: formData,
});
const data = await response.json();
result.textContent = JSON.stringify(data, null, 2);
} catch (error) {
result.textContent = JSON.stringify({ error: error.message }, null, 2);
}
});
</script>
</body>
</html>
+7
View File
@@ -0,0 +1,7 @@
from django.urls import path
from .views import ForwardSensorDataView
urlpatterns = [
path("forward/", ForwardSensorDataView.as_view(), name="forward-sensor-data"),
]
+98
View File
@@ -0,0 +1,98 @@
import json
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from ingest.constants import API_KEY, API_TARGET_URL, STATIC_SENSOR_PAYLOAD
class SensorSimulatorAppView(View):
def get(self, request):
return render(
request,
"ingest/index.html",
{
"default_payload": json.dumps(STATIC_SENSOR_PAYLOAD, indent=2),
"default_url": API_TARGET_URL,
"default_api_key": API_KEY,
},
)
@method_decorator(csrf_exempt, name="dispatch")
class ForwardSensorDataView(View):
def post(self, request):
target_url = request.POST.get("target_url", "").strip()
api_key = request.POST.get("api_key", "").strip()
if not target_url:
return JsonResponse({"error": "target_url is required"}, status=400)
if not api_key:
return JsonResponse({"error": "api_key is required"}, status=400)
payload = STATIC_SENSOR_PAYLOAD
body = json.dumps(payload).encode("utf-8")
outbound_request = Request(
target_url,
data=body,
headers={
"Content-Type": "application/json",
"api_key": api_key,
},
method="POST",
)
try:
with urlopen(outbound_request, timeout=15) as response:
response_body = response.read().decode("utf-8")
content_type = response.headers.get("Content-Type", "")
parsed_body = response_body
if "application/json" in content_type and response_body:
parsed_body = json.loads(response_body)
return JsonResponse(
{
"status": response.status,
"sent_headers": {
"Content-Type": "application/json",
"api_key": api_key,
},
"sent_payload": payload,
"response": parsed_body,
}
)
except HTTPError as exc:
error_body = exc.read().decode("utf-8", errors="replace")
return JsonResponse(
{
"error": "upstream returned an error",
"status": exc.code,
"sent_headers": {
"Content-Type": "application/json",
"api_key": api_key,
},
"sent_payload": payload,
"response": error_body,
},
status=502,
)
except URLError as exc:
return JsonResponse(
{
"error": "could not reach upstream api",
"details": str(exc.reason),
"sent_headers": {
"Content-Type": "application/json",
"api_key": api_key,
},
"sent_payload": payload,
},
status=502,
)
return HttpResponse(status=500)