picamera2: [HOW-TO] Don't take a photo after record

Hi, i am using picame2 to write a simple code to take a photo and record video. Receiver the data from TCPClient and capture or record.

import time
import os
import socket
import threading
from datetime import datetime

from picamera2 import Picamera2
from picamera2.encoders import H264Encoder
from picamera2.outputs import FfmpegOutput
from picamera2.outputs import FileOutput

picam2 = Picamera2();
isRecord = False;
isPhoto = False;
  
def camera():
  global picam2;
  global isRecord;
  global isPhoto;
  
  print("Start Camera")
  picam2.configure(picam2.create_video_configuration())
  picam2.start()
  
  try:
    while True:

      if(isPhoto):
        print("Start Photo")
        filename = "/home/raspi/img/"+ datetime.now().strftime("%d-%m-%Y-%H-%M-%S") + ".jpg";
        #picam2.start_and_capture_file(filename)

        #cfg = picam2.create_still_configuration()
        #picam2.switch_mode_and_capture_file(cfg, filename)
        
        picam2.capture_file(filename)
        isPhoto = False;
        
      if(isRecord):
        print("Start Video")
        filename = "/home/raspi/video/"+ datetime.now().strftime("%d-%m-%Y-%H-%M-%S") + ".mp4";
        #picam2.video_configuration.format = 'BGR888';
        picam2.start_and_record_video(filename, duration=900); #15p
    
  except Exception as e:
    print(f"Error: {str(e)}")

def handle_client(client_socket, client_addr):
    print(f"Connection from {client_addr}")
    thread = threading.Thread(target=camera, name='camera')
    thread.start()
    
    global picam2;
    global isRecord;
    global isPhoto;
    try:
        while True:
            # Receive data from the client
            data = client_socket.recv(1024)
            
            if not data:
                break  # No more data received, exit loop
            dataHexa = data.hex();
            #print(dataHexa)
            if(dataHexa == '01'):
              isPhoto = True;
            elif(dataHexa == '02' and isRecord == False):
              isRecord = True;
            elif(dataHexa == '03' and isRecord == True):
              print("Stop Video")
              picam2.stop_recording()
              isRecord = False;
            
            # Echo back the received data
            #client_socket.sendall(data)
    except Exception as e:
        print(f"Error: {str(e)}")
    finally:
        # Close the client socket
        client_socket.close()
        print(f"Connection with {client_addr} closed")
        thread.join()

def start_server(host, port):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(5)  # Accept up to 5 connections
    print(f"TCP server started on {host}:{port}")
    while True:
        # Wait for a client to connect
        print("Waiting for connection...")
        client_socket, client_addr = server_socket.accept()
        
        # Start a new thread to handle the client connection
        client_thread = threading.Thread(target=handle_client, args=(client_socket, client_addr))
        client_thread.start()

if __name__ == "__main__":
    start_server('0.0.0.0', 5765) 

when I record, then stop recording. After that I couldn’t record or take photos. It seems that when using the recording command and stopping recording, subsequent commands cannot be executed pls support me to fix it.

About this issue

  • Original URL
  • State: open
  • Created 3 months ago
  • Comments: 16

Most upvoted comments

Hi, I think that’s close. stop_recording will stop the camera, so either:

  • Use stop_encoder instead. That should leave the camera running.
  • Or start the camera again (picam2.start()) before calling capture_file. There will be a short delay while the camera restarts.