0

I have a Python Simple HTTP server running on a Raspberry Pi, using openCV, I am using this code below to serve a video stream from a webcam over ngrok. I want to ensure it stays running remotely, as I have had it lock-up a few times on me and I need to manually restart it. I am not sure of the reason it periodically fails as I am running the script at startup and can't seem to reproduce the error when I run it from the console.

How can I ensure the HTTP server is running? The docs don't seem to cover this, so maybe it's more of a Linux question?

Here is the working code:

import http.server
import socketserver
import cv2
import time

PORT = 8000


cap = cv2.VideoCapture(0)

class MyHandler(http.server.BaseHTTPRequestHandler):

    def do_GET(self):

        if self.path.startswith('/image'):
            self.send_response(200)
            self.send_header("Content-type", "image/jpeg")
            self.end_headers()

            ret, frame = cap.read()
            _, jpg = cv2.imencode(".jpg", frame)

            self.wfile.write(jpg)
        else:
            self.send_response(404)
        


myserver = socketserver.TCPServer(("", PORT), MyHandler) 

with myserver as httpd:
    print("Serving at port ", PORT)
    try:
        httpd.serve_forever()
    except:
        pass

My plan is to run this script in parallel:

while True:
    serverActive = #someway of confirming server is active (how can I do this?)
    if serverActive = False
        try:
            #attempt to restart server
            startServer = subprocess.Popen(["/home/pi/Desktop/startServer.py"], stdin=subprocess.PIPE)
        except:
            pass
    time.sleep(5000)

1 Answer 1

1

There are many ways to have "one of" something in a computer

It may be possible for you simply catch the port already being used (I suspect the server may raise already for this)

If not, (or if you want to run on a variety of or several ports, etc.), you may find a filesystem lock to be most convenient!

import fcntl
import os
import sys

RUN_LOC = "/var/run/myapp"
with open(RUN_LOC, r+) as fd:
    try:  # try to acquire a lock to exclude other programs from access
        fcntl.fcntl(fd, fcntl.LOCK_EX)  # lock released when fd is closed
    except OSError:  # lock failed
        sys.exit("failed to lock; owned by PID: {}".format(fd.read())
    fd.write(os.getpid())  # no competition for file as lock is owned
    fd.truncate()  # may have less content than before (PID 5 vs 10)

    # serve here in with context
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.