Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Photo Mode Skeleton #229

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
# production
/build

# media storage
/media

# misc
.DS_Store
.env
Expand All @@ -28,4 +31,4 @@ settingsTest.json
/flightlogs
.nyc_output

/local_modules/long/node_modules
/local_modules/long/node_modules
465 changes: 286 additions & 179 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
"not op_mini all"
],
"devDependencies": {
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"@babel/plugin-transform-private-property-in-object": "^7.25.9",
"@eslint/js": "^9.13.0",
"body-parser": "^1.20.2",
"chai": "^4.5.0",
Expand All @@ -75,7 +77,9 @@
"npm-run-all": "^4.1.5",
"pino-colada": "^2.2.2",
"pino-http": "^10.3.0",
"should": "^13.2.3"
"should": "^13.2.3",
"sinon": "^19.0.2",
"sinon-chai": "^3.7.0"
},
"nyc": {
"all": true,
Expand Down
160 changes: 160 additions & 0 deletions python/photomode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
# -*- coding:utf-8 vi:ts=4:noexpandtab

from picamera2 import Picamera2
from picamera2.encoders import H264Encoder

import argparse
import time, signal, os, sys, shutil

from gi.repository import GLib

# Reset the signal flag
GOT_SIGNAL = False
# Get the PID (for testing/troubleshooting)
pid = os.getpid()
print("PID is : ", pid)

def receive_signal(signum, stack):
global GOT_SIGNAL
GOT_SIGNAL = True

# Register the signal handler function to fire when signals are received
signal.signal(signal.SIGUSR1, receive_signal)

# Reset the video recording flag
VIDEO_ACTIVE = False

if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Camera control server using Picamera2")
parser.add_argument("-d", "--destination", dest="mediaPath",
help="Save captured image to PATH. Default: ../media/",
metavar="PATH",
default="../media/"
)
parser.add_argument("-m", "--mode", choices=['photo', 'video'],
dest="captureMode",
help="Capture mode options: photo [default], video", metavar="MODE",
default='photo'
)
parser.add_argument("-b", "--bitrate", metavar = "N",
type = int, dest="vidBitrate",
help="Video bitrate in bits per second. Default: 10000000",
default=10000000
)
parser.add_argument("-f", "--min-disk-space", metavar = "N",
type = int, dest="minFreeSpace",
help="Minimum free disk space (in MB) required to save files. Default: 1000 MB",
default=1000
)
args = parser.parse_args()

captureMode = args.captureMode
print("Mode is: ", captureMode)

mediaPath = args.mediaPath

# Convert to bytes
minFreeSpace = args.minFreeSpace * 1000 * 1000

# Check if the specified media directory exists
if os.path.isdir(mediaPath):
print(f"Media storage directory '{mediaPath}' exists")
# Check if we can write to the directory
try:
testfilepath = os.path.join(mediaPath, 'test.tmp')
filehandle = open( testfilepath, 'w' )
filehandle.close()
os.remove(testfilepath)
print(f"Media storage directory '{mediaPath}' is writable")
except IOError:
sys.exit(f"Unable to write to media storage directory '{mediaPath}'" )

else:
print("Media storage path '{mediaPath}' doesn't exist. Attempting to create.")
# Create the directory
try:
os.mkdir(mediaPath)
print(f"Directory '{mediaPath}' created successfully.")
except FileExistsError:
print(f"Directory '{mediaPath}' already exists.")
except PermissionError:
sys.exit(f"Permission denied: Unable to create '{mediaPath}'.")
except Exception as e:
sys.exit(f"An error occurred: {e}")

if captureMode == "video":
vidBitrate = args.vidBitrate
print("Video Bitrate is: ", vidBitrate, " (", vidBitrate / 1000000, " MBps)", sep = "")

# Wait for input on stdin
async def ainput(string: str) -> str:
await asyncio.to_thread(sys.stdout.write, f'{string} ')
name = await ainput("Your name:")

# Initialize the camera
if captureMode == "photo":
# Initialize the camera
picam2_still = Picamera2()
# By default, use the full resolution of the sensor
config = picam2_still.create_still_configuration(
main={"size": picam2_still.sensor_resolution},
buffer_count=2
)
picam2_still.configure(config)
# Keep the camera active to make responses faster
picam2_still.start()
print("Waiting 2 seconds for camera to stabilize...")
time.sleep(2)
print("Camera is ready")

elif captureMode == "video":
picam2_vid = Picamera2()
video_config = picam2_vid.create_video_configuration()
picam2_vid.configure(video_config)

encoder = H264Encoder(bitrate = vidBitrate)

def startstop_video():
global VIDEO_ACTIVE

if VIDEO_ACTIVE:
picam2_vid.stop_recording()
VIDEO_ACTIVE = False
print ("Video recording stopped.")
else:
filename = time.strftime("RPN%Y%m%d_%H%M%S.h264")
filepath = os.path.join(mediaPath, filename)
print("Recording to ", filepath)

VIDEO_ACTIVE = True
output_video = picam2_vid.start_recording(encoder, filepath)

try:
# Wait for a signal to arrive
while True:
if (GOT_SIGNAL and (captureMode == "photo")):
GOT_SIGNAL = False

# Get the amount of free disk space, in bytes
freeDiskSpace = shutil.disk_usage(mediaPath)[2]

if freeDiskSpace < minFreeSpace:
print(f"Free disk space is below the minimum of {minFreeSpace} MiB. Image not recorded.")
else:
print("Received signal.SIGUSR1. Capturing photo.")
filename = time.strftime("RPN%Y%m%d_%H%M%S.jpg")
filepath = os.path.join(mediaPath, filename)
print(filepath)
output_orig = picam2_still.capture_file(filepath)

elif (GOT_SIGNAL and (captureMode == "video")):
GOT_SIGNAL = False
print("Received signal.SIGUSR1.")
startstop_video()

# Wait for a signal
signal.pause()
#loop.run()
except:
print("Exiting Photo/Video Server")
61 changes: 57 additions & 4 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,43 @@ vManager.eventEmitter.on('videostreaminfo', (msg, senderSysId, senderCompId, tar
}
})

// Got a CAMERA_SETTINGS event, send to flight controller
vManager.eventEmitter.on('camerasettings', (msg, senderSysId, senderCompId, targetComponent) => {
try {
if (fcManager.m) {
fcManager.m.sendCommandAck(common.CameraSettings.MSG_ID, 0, senderSysId, senderCompId, targetComponent)
fcManager.m.sendData(msg, senderCompId)
}
} catch (err) {
console.log(err)
}
})

// Got a DO_DIGICAM_CONTROL event, send to flight controller
vManager.eventEmitter.on('digicamcontrol', (senderSysId, senderCompId, targetComponent) => {
console.log("index.js:digicamcontrol event received")
try {
if (fcManager.m) {
// 203 = MAV_CMD_DO_DIGICAM_CONTROL
fcManager.m.sendCommandAck(203, 0, senderSysId, senderCompId, targetComponent)
}
} catch (err) {
console.log(err)
}
})

// Got a CAMERA_TRIGGER event, send to flight controller
vManager.eventEmitter.on('cameratrigger', (msg, senderSysId, senderCompId, targetComponent) => {
try {
if (fcManager.m) {
fcManager.m.sendCommandAck(common.CameraTrigger.MSG_ID, 0, senderSysId, senderCompId, targetComponent)
fcManager.m.sendData(msg, senderCompId)
}
} catch (err) {
console.log(err)
}
})

// Connecting the flight controller datastream to the logger
// and ntrip and video
fcManager.eventEmitter.on('gotMessage', (packet, data) => {
Expand Down Expand Up @@ -428,7 +465,7 @@ app.get('/api/softwareinfo', (req, res) => {

app.get('/api/videodevices', (req, res) => {
vManager.populateAddresses()
vManager.getVideoDevices((err, devices, active, seldevice, selRes, selRot, selbitrate, selfps, SeluseUDP, SeluseUDPIP, SeluseUDPPort, timestamp, fps, FPSMax, vidres, useCameraHeartbeat, selMavURI) => {
vManager.getVideoDevices((err, devices, active, seldevice, selRes, selRot, selbitrate, selfps, SeluseUDP, SelusePhotoMode, SeluseUDPIP, SeluseUDPPort, timestamp, fps, FPSMax, vidres, useCameraHeartbeat, useMavControl, selMavURI, selMediaPath) => {
if (!err) {
res.setHeader('Content-Type', 'application/json')
res.send(JSON.stringify({
Expand All @@ -443,14 +480,17 @@ app.get('/api/videodevices', (req, res) => {
bitrate: selbitrate,
fpsSelected: selfps,
UDPChecked: SeluseUDP,
photoMode: SelusePhotoMode,
useUDPIP: SeluseUDPIP,
useUDPPort: SeluseUDPPort,
timestamp,
error: null,
fps: fps,
FPSMax: FPSMax,
enableCameraHeartbeat: useCameraHeartbeat,
mavStreamSelected: selMavURI
enableMavControl: useMavControl,
mavStreamSelected: selMavURI,
mediaPath: selMediaPath
}))
} else {
res.setHeader('Content-Type', 'application/json')
Expand Down Expand Up @@ -697,22 +737,28 @@ app.post('/api/startstopvideo', [check('active').isBoolean(),
check('height').if(check('active').isIn([true])).isInt({ min: 1 }),
check('width').if(check('active').isIn([true])).isInt({ min: 1 }),
check('useUDP').if(check('active').isIn([true])).isBoolean(),
check('usePhotoMode').if(check('active').isIn([true])).isBoolean(),
check('useTimestamp').if(check('active').isIn([true])).isBoolean(),
check('useCameraHeartbeat').if(check('active').isIn([true])).isBoolean(),
check('useMavControl').if(check('active').isIn([true])).isBoolean(),
check('useUDPPort').if(check('active').isIn([true])).isPort(),
check('useUDPIP').if(check('active').isIn([true])).isIP(),
check('bitrate').if(check('active').isIn([true])).isInt({ min: 50, max: 50000 }),
check('format').if(check('active').isIn([true])).isIn(['video/x-raw', 'video/x-h264', 'image/jpeg']),
check('fps').if(check('active').isIn([true])).isInt({ min: -1, max: 100 }),
check('rotation').if(check('active').isIn([true])).isInt().isIn([0, 90, 180, 270])], (req, res) => {
check('rotation').if(check('active').isIn([true])).isInt().isIn([0, 90, 180, 270])],
check('mediaPath').if(check('active').isIn([true])).isLength({ min: 2 }), (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
winston.error('Bad POST vars in /api/startstopvideo ', { message: errors.array() })
const ret = { streamingStatus: false, streamAddresses: [], error: ['Error ' + JSON.stringify(errors.array())] }
return res.status(422).json(ret)
}
// user wants to start/stop video streaming
vManager.startStopStreaming(req.body.active, req.body.device, req.body.height, req.body.width, req.body.format, req.body.rotation, req.body.bitrate, req.body.fps, req.body.useUDP, req.body.useUDPIP, req.body.useUDPPort, req.body.useTimestamp, req.body.useCameraHeartbeat, req.body.mavStreamSelected, (err, status, addresses) => {
vManager.startStopStreaming(req.body.active, req.body.device, req.body.height, req.body.width, req.body.format,
req.body.rotation, req.body.bitrate, req.body.fps, req.body.useUDP, req.body.usePhotoMode, req.body.useUDPIP,
req.body.useUDPPort, req.body.useTimestamp, req.body.useCameraHeartbeat, req.body.useMavControl, req.body.mavStreamSelected,
req.body.mediaPath, (err, status, addresses) => {
if (!err) {
res.setHeader('Content-Type', 'application/json')
const ret = { streamingStatus: status, streamAddresses: addresses }
Expand All @@ -726,6 +772,13 @@ app.post('/api/startstopvideo', [check('active').isBoolean(),
})
})

// Capture a single still photo when in photo mode
app.post('/api/capturestillphoto', function (req, res) {
vManager.captureStillPhoto()
console.log(req.body)
res.end();
})

// Get details of a network connection by connection ID
app.post('/api/networkIP', [check('conName').isUUID()], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
Expand Down
Loading
Loading