Commit 8b9dcaa4 authored by Nathan ROCHER's avatar Nathan ROCHER
Browse files

Update stream.py

parent caba46ba
import io
import json
from os import listdir, remove
from os.path import isfile, join
import os
import picamera
import socket
import logging
import socketserver
from threading import Condition
from http import server
import datetime
import time
import ffmpeg
#Récupération de l'ip de la raspberry
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
print("Votre ip est : " + ip + "\n")
except:
print("Connexion internet non trouvé")
#initialisation de la page a charger en html
#la résolution de l'image ce change ici ainsi que le titre ou meme tout autre information que vous voudriez ajouter sur la page
PAGE="""\
<html>
<head>
<title>Raspberry Pi - Surveillance Camera</title>
<title>Caméra de surveillance</title>
</head>
<body>
<center><h1>Caméra de surveillance</h1></center>
<center><img src="stream.mjpg" style="width:50%" ></center>
</body>
</html>
"""
STREAMING="""\
<html>
<head>
<title>Caméra de surveillance</title>
</head>
<body>
<center><h1>Raspberry Pi - Surveillance Camera</h1></center>
<center><img src="stream.mjpg" width="1080" height="720"></center>
<video controls src="__URL__" style="width:50%" autoplay ></video>
</body>
</html>
"""
RECORDING = False
class StreamingOutput(object):
def __init__(self):
self.frame = None
......@@ -40,8 +45,6 @@ class StreamingOutput(object):
def write(self, buf):
if buf.startswith(b'\xff\xd8'):
# New frame, copy the existing buffer's content and notify all
# clients it's available
self.buffer.truncate()
with self.condition:
self.frame = self.buffer.getvalue()
......@@ -62,7 +65,57 @@ class StreamingHandler(server.BaseHTTPRequestHandler):
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == '/stream.mjpg':
elif "files" in self.path :
onlyfiles = [f for f in listdir("./RECORD") if isfile(join("./RECORD", f))]
content = json.dumps(onlyfiles).encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif "download-file" in self.path:
file = self.path.split("/")[2].replace("/", "")
self.send_response(200)
self.send_header('Content-Disposition', 'attachment')
self.end_headers()
with open("./RECORD/" + file, 'rb') as file:
self.wfile.write(file.read())
elif "delete-file" in self.path:
file = self.path.split("/")[2].replace("/", "")
remove("./RECORD/" + file)
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write("Fichier supprimé".encode('utf-8'))
elif "stream-file" in self.path:
file = self.path.split("/")[2].replace("/", "")
content = STREAMING.replace("__URL__", "../download-file/"+file).encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif "record" in self.path :
self.send_response(200)
self.end_headers()
self.wfile.write("ok".encode('utf-8'))
global RECORDING
if RECORDING == False :
RECORDING = True
today = datetime.datetime.today()
name = today.strftime("%d-%m-%Y_%Hh%M") #on met comme nom de fichier l'heure et la date de l'enregistrement (hh:mm:ss-JJ-MM-YY)
camera.start_recording("./RECORD_RAW/" + name + ".h264", format="h264", splitter_port=1) #début du record avec nom du fichier
print ("Enregistrement démarré : "+ name)
time.sleep(30)
camera.stop_recording()
print ("Fin enregistrement")
RECORDING = False
ffmpeg.input("./RECORD_RAW/" + name + ".h264").output("./RECORD/" + name + '.mp4').run()
remove("./RECORD_RAW/" + name + ".h264")
elif "stream.mjpg" in self.path :
self.send_response(200)
self.send_header('Age', 0)
self.send_header('Cache-Control', 'no-cache, private')
......@@ -70,7 +123,7 @@ class StreamingHandler(server.BaseHTTPRequestHandler):
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
self.end_headers()
try:
while True:
while True:
with output.condition:
output.condition.wait()
frame = output.frame
......@@ -81,28 +134,27 @@ class StreamingHandler(server.BaseHTTPRequestHandler):
self.wfile.write(frame)
self.wfile.write(b'\r\n')
except Exception as e:
logging.warning(
'Removed streaming client %s: %s',
self.client_address, str(e))
logging.warning('Removed streaming client %s: %s', self.client_address, str(e))
else:
self.send_error(404)
self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer): #serveur de stream
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
with picamera.PiCamera(resolution='720x480', framerate=15) as camera:
output = StreamingOutput()
with picamera.PiCamera(resolution='1296x730', framerate=30) as camera:
camera.rotation = 0 #changer cette variable pour effectuer une rotation de l'image (en degrés)
camera.start_recording(output, format='mjpeg')
if not os.path.exists("./RECORD_RAW/"):
os.makedirs("./RECORD_RAW/")
if not os.path.exists("./RECORD/"):
os.makedirs("./RECORD/")
output = StreamingOutput()
camera.start_recording(output, format='mjpeg', splitter_port=0)
try:
print("Demarrage du stream")
address = ('', 8080) #port utilisé
address = ('', 8080)
server = StreamingServer(address, StreamingHandler)
server.serve_forever() #le lancer pour toujours
server.serve_forever()
finally:
camera.stop_recording()
camera.stop_recording()
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment