Adding initial camera functions
This commit is contained in:
37
src/app.py
37
src/app.py
@@ -1,6 +1,10 @@
|
||||
from collections.abc import Generator
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import Flask, Response, jsonify
|
||||
from flask import Flask, Response, jsonify, render_template
|
||||
|
||||
from src.camera import camera
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@@ -18,5 +22,34 @@ def heartbeat() -> tuple[Response, int]:
|
||||
)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index() -> str:
|
||||
return render_template("index.html")
|
||||
|
||||
|
||||
@app.post("/camera/start")
|
||||
def camera_start() -> tuple[Response, int]:
|
||||
camera.start()
|
||||
return jsonify({"status": "started"}), 200
|
||||
|
||||
|
||||
@app.post("/camera/stop")
|
||||
def camera_stop() -> tuple[Response, int]:
|
||||
camera.stop()
|
||||
return jsonify({"status": "stopped"}), 200
|
||||
|
||||
|
||||
@app.get("/camera/stream")
|
||||
def camera_stream() -> Response:
|
||||
def generate() -> Generator[bytes, Any, Any]:
|
||||
for frame in camera.frames():
|
||||
yield (b"--frame\r\n" b"Content-Type: video/H264\r\n\r\n" + frame + b"\r\n")
|
||||
|
||||
return Response(
|
||||
generate(),
|
||||
mimetype="multipart/x-mixed-replace; boundary=frame",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(debug=True)
|
||||
app.run(host="0.0.0.0", port=5000, debug=True)
|
||||
|
||||
82
src/camera.py
Normal file
82
src/camera.py
Normal file
@@ -0,0 +1,82 @@
|
||||
import logging
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
try:
|
||||
from picamera2 import Picamera2
|
||||
from picamera2.encoders import H264Encoder
|
||||
from picamera2.outputs import FileOutput
|
||||
|
||||
PICAMERA_AVAILABLE = True
|
||||
except ImportError:
|
||||
PICAMERA_AVAILABLE = False
|
||||
logger.warning("picamera2 not available — running in mock mode")
|
||||
|
||||
|
||||
class StreamOutput:
|
||||
"""Thread-safe buffer that holds the latest H.264 frame."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.frame: bytes = b""
|
||||
self.condition = threading.Condition()
|
||||
|
||||
def write(self, data: bytes) -> None:
|
||||
with self.condition:
|
||||
self.frame = data
|
||||
self.condition.notify_all()
|
||||
|
||||
|
||||
class Camera:
|
||||
def __init__(self) -> None:
|
||||
self._picam: Picamera2 | None = None
|
||||
self._output: StreamOutput | None = None
|
||||
self._encoder: H264Encoder | None = None
|
||||
self.running = False
|
||||
|
||||
def start(self) -> None:
|
||||
if self.running:
|
||||
return
|
||||
if not PICAMERA_AVAILABLE:
|
||||
logger.info("Mock camera started")
|
||||
self.running = True
|
||||
return
|
||||
|
||||
self._picam = Picamera2()
|
||||
config = self._picam.create_video_configuration(
|
||||
main={"size": (1280, 720)},
|
||||
)
|
||||
self._picam.configure(config)
|
||||
self._output = StreamOutput()
|
||||
self._encoder = H264Encoder(bitrate=2_000_000)
|
||||
self._picam.start_recording(self._encoder, FileOutput(self._output))
|
||||
self.running = True
|
||||
logger.info("Camera started")
|
||||
|
||||
def stop(self) -> None:
|
||||
if not self.running:
|
||||
return
|
||||
if self._picam:
|
||||
self._picam.stop_recording()
|
||||
self._picam.close()
|
||||
self._picam = None
|
||||
self.running = False
|
||||
logger.info("Camera stopped")
|
||||
|
||||
def frames(self) -> Iterator[bytes]:
|
||||
"""Yield H.264 frames for multipart streaming."""
|
||||
if not PICAMERA_AVAILABLE:
|
||||
# yield a small empty frame in mock mode
|
||||
while self.running:
|
||||
yield b""
|
||||
return
|
||||
assert self._output is not None
|
||||
while self.running:
|
||||
with self._output.condition:
|
||||
self._output.condition.wait()
|
||||
frame = self._output.frame
|
||||
yield frame
|
||||
|
||||
|
||||
camera = Camera()
|
||||
143
src/templates/index.html
Normal file
143
src/templates/index.html
Normal file
@@ -0,0 +1,143 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Pi Camera</title>
|
||||
<style>
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
background: #0f0f0f;
|
||||
color: #f0f0f0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100vh;
|
||||
gap: 1.5rem;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.4rem;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
#preview {
|
||||
width: 100%;
|
||||
max-width: 720px;
|
||||
aspect-ratio: 16/9;
|
||||
background: #1a1a1a;
|
||||
border: 1px solid #333;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #555;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
#preview img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 0.6rem 2rem;
|
||||
font-size: 1rem;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
#btn-start {
|
||||
background: #22c55e;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
#btn-stop {
|
||||
background: #ef4444;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
#status {
|
||||
font-size: 0.85rem;
|
||||
color: #888;
|
||||
min-height: 1.2em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Pi Camera Stream</h1>
|
||||
|
||||
<div id="preview">
|
||||
<span id="placeholder">Stream not started</span>
|
||||
<img id="stream-img" alt="Camera stream" />
|
||||
</div>
|
||||
|
||||
<div class="controls">
|
||||
<button id="btn-start">Start</button>
|
||||
<button id="btn-stop" disabled>Stop</button>
|
||||
</div>
|
||||
|
||||
<p id="status"></p>
|
||||
|
||||
<script>
|
||||
const btnStart = document.getElementById("btn-start");
|
||||
const btnStop = document.getElementById("btn-stop");
|
||||
const streamImg = document.getElementById("stream-img");
|
||||
const placeholder = document.getElementById("placeholder");
|
||||
const status = document.getElementById("status");
|
||||
|
||||
async function postAction(url) {
|
||||
const res = await fetch(url, { method: "POST" });
|
||||
return res.json();
|
||||
}
|
||||
|
||||
btnStart.addEventListener("click", async () => {
|
||||
btnStart.disabled = true;
|
||||
status.textContent = "Starting…";
|
||||
await postAction("/camera/start");
|
||||
streamImg.src = "/camera/stream";
|
||||
streamImg.style.display = "block";
|
||||
placeholder.style.display = "none";
|
||||
btnStop.disabled = false;
|
||||
status.textContent = "Streaming";
|
||||
});
|
||||
|
||||
btnStop.addEventListener("click", async () => {
|
||||
btnStop.disabled = true;
|
||||
status.textContent = "Stopping…";
|
||||
streamImg.style.display = "none";
|
||||
streamImg.src = "";
|
||||
placeholder.style.display = "block";
|
||||
await postAction("/camera/stop");
|
||||
btnStart.disabled = false;
|
||||
status.textContent = "Stream stopped";
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Reference in New Issue
Block a user