Display all params

This commit is contained in:
Nicolas Bertrand 2025-09-04 11:07:27 +02:00
parent 7eb06bbd57
commit 7ea52bc571
2 changed files with 116 additions and 116 deletions

View File

@ -1,4 +1,4 @@
from flask import Blueprint, render_template, request, redirect
from flask import Blueprint, render_template, request, send_file, jsonify
import json
from .. import camera as C
@ -11,61 +11,93 @@ blueprint = Blueprint('camera', __name__)
@blueprint.route('/')
def get():
"""
Returns the page showing camera configuration
Returns the page showing camera configuration for all parameters in capturesettings and imgsettings,
grouped by section.
"""
# Load configCamera.json
with open('configCamera.json', 'r') as f:
config = json.load(f)
# Extract shutterspeed choices and current value
shutterspeed = config['main']['capturesettings']['shutterspeed']
shutterspeed_choices = [
{'value': c.get('id', idx), 'label': c['label']}
for idx, c in enumerate(shutterspeed['Choices'])
]
shutterspeed_current = shutterspeed['Current']
# Extract aperture choices and current value
aperture = config['main']['capturesettings']['aperture']
aperture_choices = [
{'value': c.get('id', idx), 'label': c['label']}
for idx, c in enumerate(aperture['Choices'])
]
aperture_current = aperture['Current']
grouped_params = []
for section in ['capturesettings', 'imgsettings']:
section_params = []
settings = config['main'].get(section, {})
for param_name, param in settings.items():
if 'Choices' in param and isinstance(param['Choices'], list) and param['Choices']:
choices = [
{'value': c.get('id', idx), 'label': c['label']}
for idx, c in enumerate(param['Choices'])
]
if len(choices) > 1:
section_params.append({
'name': param_name,
'label': param.get('Label', param_name.capitalize()),
'choices': choices,
'current': param.get('Current', '')
})
if section_params:
grouped_params.append({
'section': section,
'params': section_params
})
import pprint
pprint.pprint(grouped_params)
return render_template(
'camera.html',
shutterspeed_choices=shutterspeed_choices,
shutterspeed_current=shutterspeed_current,
aperture_choices=aperture_choices,
aperture_current=aperture_current
grouped_params=grouped_params
)
@blueprint.route('/set', methods=['POST'])
def set_camera_settings():
"""
Receives and processes new camera settings (shutterspeed, aperture) from the client.
Receives and processes new camera settings for all parameters from the client.
"""
data = request.get_json()
shutterspeed = data.get('shutterspeed')
aperture = data.get('aperture')
if shutterspeed is not None:
print(f"Received shutterspeed: {shutterspeed}")
C.set_config('shutterspeed', shutterspeed)
if aperture is not None:
print(f"Received aperture: {aperture}")
C.set_config('aperture', aperture)
return {'status': 'ok', 'shutterspeed': shutterspeed, 'aperture': aperture}
# filepath: /home/nicolas/dev/git/git.polymny.net/source/nenuscanner/src/nenuscanner/routes/camera.py
from flask import send_file
updated = {}
for key, value in data.items():
print(f"Received {key}: {value}")
C.set_config(key, value)
updated[key] = value
return {'status': 'ok', **updated}
@blueprint.route('/feed.jpg')
def camera_feed():
return send_file('static/feed.jpg', mimetype='image/jpeg')
@blueprint.route('/config', methods=['GET'])
def get_camera_config():
"""
Returns grouped camera parameters as JSON for frontend JS.
"""
with open('configCamera.json', 'r') as f:
config = json.load(f)
grouped_params = []
for section in ['capturesettings', 'imgsettings']:
section_params = []
settings = config['main'].get(section, {})
for param_name, param in settings.items():
if 'Choices' in param and isinstance(param['Choices'], list) and param['Choices']:
choices = [
{'value': c.get('id', idx), 'label': c['label']}
for idx, c in enumerate(param['Choices'])
]
if len(choices) > 1:
section_params.append({
'name': param_name,
'label': param.get('Label', param_name.capitalize()),
'choices': choices,
'current': param.get('Current', '')
})
if section_params:
grouped_params.append({
'section': section,
'params': section_params
})
return jsonify(grouped_params)

View File

@ -3,54 +3,37 @@
{% block content %}
<section class="section">
<div class="container">
<h1 class="title">Configurer la camera </h1>
<div class="field is-grouped is-grouped-multiline">
<div class="control">
<button> Lire la configuration actuelle</button>
</div>
</div>
<form action="/camera/set" method="POST">
<h1 class="title">Configurer la camera</h1>
<form id="camera-config-form">
<div class="columns">
<!-- Left column: Camera controls -->
<div class="column is-half">
<div class="field">
<label class="label" for="shutterspeed">Shutter Speed:</label>
<div class="control">
<div class="select is-fullwidth">
<select id="shutterspeed" name="shutterspeed">
{% for choice in shutterspeed_choices %}
<option value="{{ choice.value }}" {% if choice.label == shutterspeed_current %}selected{% endif %}>
{{ choice.value }} {{ choice.label }}
</option>
{% endfor %}
</select>
{% for group in grouped_params %}
<div class="box">
<h2 class="subtitle has-text-weight-bold">
{{ group.section | replace('settings', ' Settings') | capitalize }}
</h2>
{% for param in group.params %}
<div class="field">
<label class="label" for="{{ param.name }}">{{ param.label }}:</label>
<div class="control">
<div class="select is-fullwidth">
<select id="{{ param.name }}" name="{{ param.name }}">
{% for choice in param.choices %}
<option value="{{ choice.value }}" {% if choice.label == param.current %}selected{% endif %}>
{{ choice.label }} ({{ choice.value }})
</option>
{% endfor %}
</select>
</div>
</div>
<div class="control mt-2">
<button class="button is-small is-primary" type="button" onclick="setConfig('{{ param.name }}')">Set</button>
</div>
</div>
<div class="control mt-2">
<button class="button is-small is-primary" name="validate-shutterspeed">Set</button>
</div>
</div>
<div class="field">
<label class="label" for="aperture">Aperture:</label>
<div class="control">
<div class="select is-fullwidth">
<select id="aperture" name="aperture">
{% for choice in aperture_choices %}
<option value="{{ choice.value }}" {% if choice.label == aperture_current %}selected{% endif %}>
{{ choice.value }} {{ choice.label }}
</option>
{% endfor %}
</select>
</div>
</div>
<div class="control mt-2">
<button class="button is-small is-primary" name="validate-aperture" type="button">Set</button>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
<!-- Right column: Camera preview -->
<div class="column is-half has-text-centered">
<figure class="image is-4by3" style="max-width: 480px; margin: auto;">
<img id="camera-preview" src="/camera/feed.jpg?{{ range(1000000)|random }}" alt="Camera Preview" style="border: 1px solid #ccc;">
@ -65,42 +48,27 @@
{% block extrajs %}
<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('button[name="validate-shutterspeed"]').addEventListener('click', async function(e) {
e.preventDefault();
const value = document.getElementById('shutterspeed').value;
await fetch('/camera/set', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ shutterspeed: value })
});
location.reload();
});
function setConfig(paramName) {
const value = document.getElementById(paramName).value;
fetch('/camera/set', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ [paramName]: value })
}).then(() => location.reload());
}
document.querySelector('button[name="validate-aperture"]').addEventListener('click', async function(e) {
e.preventDefault();
const value = document.getElementById('aperture').value;
await fetch('/camera/set', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ aperture: value })
});
location.reload();
});
window.refreshPreview = function() {
const img = document.getElementById('camera-preview');
const url = '/camera/feed.jpg?' + new Date().getTime();
img.src = url;
}
//setInterval(window.refreshPreview, 2000);
// Refresh preview image without reloading the page
window.refreshPreview = function() {
const img = document.getElementById('camera-preview');
const url = '/camera/feed.jpg?' + new Date().getTime();
img.src = url;
}
// Automatically refresh every 2 seconds
setInterval(window.refreshPreview, 2000);
});
fetch('/camera/config')
.then(response => response.json())
.then(data => {
// data is grouped_params, you can now dynamically build selects in JS
console.log(data);
});
</script>
{% endblock extrajs %}