I am parsing embedded KLV data in an MPEG-TS video stream sent to a UDP port from a UAV to use in a real time map. I am getting 25 packets per second (tied to the video frame rate) at the moment and can save all of this data but I want to only save the data once a second. Every 40ms is too much. I have attempted using threading to run 2 functions. One to get the data and write to a global variable and one to read that variable every second and print/save.
#setup code (UDP socket etc)
#global variable for KLV metadata
metadata = {}
#Function to parse KLV data from UDP Stream using klvdata module
def getData():
while True:
data, address = sock.recvfrom(2048)
for packet in klvdata.StreamParser(data):
global metadata
metadata=packet.MetadataList()
#Prints selected keys at 1 sec intervals. Add more keys as required
def printData():
while True:
global metadata
time.sleep(1)
long = round(float(metadata[14][3]),6)
print(f"Sensor Longitude: {long}")
lat = round(float(metadata[13][3]),6)
print(f"Sensor Latitude: {lat}")
if __name__ == '__main__':
t1 = Thread(target=getData)
t1.start()
t2 = Thread(target=printData)
t2.start()
This has had mixed success. If the UDP stream is not running I get a key error as the dict is empty and the while loop in the printData func is infinite regardless of new data or not. I understand both of errors and why they happen. What I am wondering is if there is a better way to do this than the path I'm on now.
Thanks
This code works so far but I will test more.
#global variable for KLV metadata
metadata = None
#Function to parse KLV data from UDP Stream using klvdata module
def getData():
global metadata
while True:
data, address = sock.recvfrom(2048)
for packet in klvdata.StreamParser(data):
metadata=packet.MetadataList()
#Prints selected keys at 1 sec intervals. Add more keys as required
def printData():
global metadata
while True:
time.sleep(1)
if metadata is not None:
long = round(float(metadata[14][3]),6)
print(f"Sensor Longitude: {long}")
lat = round(float(metadata[13][3]),6)
print(f"Sensor Latitude: {lat}")
metadata = None