While loop blocks when reading a buffer and writing to fifo

43 Views Asked by At

I have a while loop that reads data from a buffer and writes it to a named pipe.

The loop never executes, unless I add a small sleep interval inside the loop.

This to me suggests there is a sync issue between reading data from the buffer and writing it to the pipe.

If my hunch is correct, how does one solve this kind of issue in python?

Additional detail I have a golang program that has the pipe open and waits on the python script to send data to it

from picamera2 import Picamera2
from picamera2.encoders import H264Encoder
from picamera2.outputs import FileOutput
from picamera2.outputs import CircularOutput
import time
import sys
import os
import io
import signal

def signal_handler(sig, frame):
    print('Received CTRL+C, exiting...')
    sys.exit(0)

picam2=Picamera2()
sensor_modes = picam2.sensor_modes

#loop through the sensor modes and print them
print('Sensor Modes:')
for mode in sensor_modes:
    print(mode)

raw_modes = picam2._get_raw_modes()

#loop through the raw modes and print them
print('Raw Modes:')
for mode in raw_modes:
    print(mode)

config = picam2.create_video_configuration(main={'size': (1280, 800), 'format':'YUV420'}, raw={'size': (2028,1520)})
picam2.configure(config)

fifo_path = os.path.abspath('../pipe1')
#check if the fifo exists
if not os.path.exists(fifo_path):
    print('error: fifo does not exist')
    sys.exit(1)
print ('opening fifo')
try:
    fifo = io.open(fifo_path, 'wb', buffering=0)
except FileNotFoundError:
    print("error: fifo '{}' does not exist.".format(fifo_path))
    sys.exit(1)
except PermissionError:
    print("error: permission denied to write to FIFO '{}'.".format(fifo_path))
    sys.exit(1)
except Exception as e:
    print("error:", e)
    sys.exit(1)
else:
    print("fifo opened successfully.")

encoder = H264Encoder(bitrate=20000000, repeat=True, iperiod=7, framerate=30)

#buffer_capacity = bytearray(30)
buffer = io.BytesIO()
output = CircularOutput(buffer, buffersize=1)

print('starting recording')
picam2.start_recording(encoder, output)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

#Continuously write the buffer to the fifo
try:
    while True:
        time.sleep(15/1000)
        buffer.seek(0)
        data = buffer.read()
        fifo.write(data)
        buffer.truncate(0)
except Exception as e:
    print("error:", e)
finally:
    picam2.stop_recording()
    fifo.close()
    print('fifo closed')
    sys.exit(0)
0

There are 0 best solutions below