Skip to content

Instantly share code, notes, and snippets.

@nickoala
Last active November 9, 2019 06:54
Show Gist options
  • Save nickoala/2a06f16e52881c1291cd211c08f21e1d to your computer and use it in GitHub Desktop.
Save nickoala/2a06f16e52881c1291cd211c08f21e1d to your computer and use it in GitHub Desktop.
""" Raspberry Pi + GPS Car Camera
Achieved with three threads:
1. Main thread -
Start preview and recording.
2. GPS thread -
Read GPS location.
3. Annotate thread -
Put GPS location and datetime on image.
Refresh every one second to simulate a running clock.
Should be coupled with a cron job which deletes old video clips,
to prevent disk from filling up.
"""
import picamera
from datetime import datetime
import threading
import time
import os
import sys
import gpsd
video_size = (640, 480)
preview_dimension = (160, 0, 640, 480) # x, y, w, h
clip_directory = sys.argv[1]
def record(camera):
def datetime_filename():
while 1:
yield (
os.path.join(
clip_directory,
datetime.now().strftime('%Y%m%d-%H%M.h264')))
def seconds_to_go():
length = 15 * 60
now = datetime.now()
seconds = now.minute * 60 + now.second
return length - seconds % length
for filename in camera.record_sequence(datetime_filename()):
camera.wait_recording(seconds_to_go())
latest_location = None
def gpsread():
global latest_location
gpsd.connect()
while 1:
try:
packet = gpsd.get_current()
latest_location = packet.position()
except gpsd.NoFixError:
latest_location = None
finally:
time.sleep(1)
# Separate annotation from GPS because I want to refresh the text
# once per second to give an illusion of a running clock.
def annotate(camera):
def compose_text(dt, location):
if location:
lat, lon = location
loctext = '{:.4f}{} {:.4f}{}'.format(
lat, 'N' if lat >= 0 else 'S',
lon, 'E' if lon >= 0 else 'W')
else:
loctext = '--lat-- --lon--'
return dt.strftime('%Y-%m-%d %H:%M:%S ') + loctext
global latest_location
camera.annotate_text_size = 24
while 1:
camera.annotate_text = compose_text(datetime.now(),
latest_location)
time.sleep(1)
camera = picamera.PiCamera(resolution=video_size, framerate=30)
#camera.hflip = True
#camera.vflip = True
#camera.rotation = 90
gps_thread = threading.Thread(target=gpsread)
gps_thread.daemon = True
gps_thread.start()
annotate_thread = threading.Thread(target=annotate, args=[camera])
annotate_thread.daemon = True
annotate_thread.start()
camera.start_preview(fullscreen=False, window=preview_dimension)
record(camera)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment