web monitor based on raspberry pi 4b


闲来无事,利用校园网搭建了一个局域网内的监控,主要用了python和raspberrypicam自带的库。

实现过于简单了,直接贴上源代码,如下:

import io
import logging
import socketserver
from http import server
from threading import Condition
from picamera2 import Picamera2
from picamera2.encoders import MJPEGEncoder
from picamera2.outputs import FileOutput
PAGE = """\
<html>
<head>
<title>picamera2 MJPEG streaming</title>
</head>
<body>
<h1>streaming:</h1>
< img src="stream.mjpg" width="640" height="480" />
</body>
</html>
"""
class StreamingOutput(io.BufferedIOBase):
    def __init__(self):
        self.frame = None
        self.condition = Condition()
    def write(self, buf):
        with self.condition:
            self.frame = buf
            self.condition.notify_all()
class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            content = PAGE.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 self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    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))
        else:
            self.send_error(404)
            self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True
picam2 = Picamera2()
picam2.configure(picam2.create_video_configuration(main={"size": (640, 480)}))
output = StreamingOutput()
picam2.start_recording(MJPEGEncoder(), FileOutput(output))
try:
    address = ('', 8000)
    server = StreamingServer(address, StreamingHandler)
    server.serve_forever()
finally:
    picam2.stop_recording()

就像代码中显示的一样,你可以调整视频流格式,解码方法,分辨率,以及你的端口。

要注意picamera2库的部分配置写法和picamera库有所区别,根据官方文档做些修改就可以了,同时如果你和我一样使用最新的raspbian和4b,在rasp-config中一定切记把legacy camera给关闭。

最后的访问方法是在局域网内输入http://‘树莓派的ip’:‘代码中开启的端口’就可以直接看到自己的监控画面了。

就像这样。

如果想要公网访问,使用内网穿透,也可以轻松实现。我使用的内网穿透工具叫做cpolar,付费制但是比较简洁易用,只要使用官网给出的方法,在python运行的同时开启一个穿透的进程即可。

user@raspberrypi:~$ cpolar http 8000

这样就能得到一个cpolar给出的临时网址,就可以实现公网访问了。在校外监视监视室友上下床还是挺有意思的。

关于cpolar更多的用法可以去官网看看,还是挺不错的:cpolar.com


6 条回复

  1. Akilia 的头像
    Akilia

    不觉得很酷吗?!很符合我对random9自制网站的想象!!

    1. Random9 的头像
      Random9

      嗯嗯😘😘😘😘

  2. Akilia9 的头像
    Akilia9

    我将要发表垃圾评论🚮

    1. Random9 的头像
      Random9

      好的

  3. 漂流贯头 的头像
    漂流贯头

    很性感设计!爱来自土雷芒果💓💓💓

  4. Random80 的头像
    Random80

    ohmygod

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

© Random9’s Pitlane