Skip to content

Technical Documentation

Camera Tuning Page

Purpose

The Camera Tuning Page is designed to allow users to input and modify variables related to camera settings in a user-friendly manner. The primary goal is to collect user-inputted values, convert them into JSON format, and then update the variables.json file.

HTML Structure

The HTML code consists of input fields with the number type, each labeled for their independent ID. Below is a snippet representing part of the form:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<div>
    <H3>Lower</H3>
    <label for="WhiteHueLower">Hue:</label>
    <input type="number" id="WhiteHueLower">
    <label for="WhiteSaturationLower">Saturation:</label>
    <input type="number" id="WhiteSaturationLower">
    <label for="WhiteLightnessLower">Lightness:</label>
    <input type="number" id="WhiteLightnessLower">
</div>
</br>
<button onclick="UpdateCamera()">Submit</button>

JavaScript Function: UpdateCamera()

Input Collection

The function starts by collecting values from input fields based on their unique IDs. For example:

1
var RedHueUpper = document.getElementById("RedHueUpper").value;

Fetching variables.json

The function then fetches the variables.json file and converts the response into jsonData. It updates jsonData if any values from the input fields are not null or an empty string, parsing them into integers.

1
2
3
4
5
6
7
8
fetch('variables.json')
    .then(response => response.json())
    .then(jsonData => {
        // Update jsonData with input field values if filled
        if (RedHueUpper != null && RedHueUpper != "")
            jsonData.colorValues.red.upperValue.hue = parseInt(RedHueUpper);
        // ... (similar logic for other color variables)
        console.log(jsonData); // Debug code

Updating and Sending Data

After updating jsonData, it is converted back to JSON format. The function then fetches a PHP file (updateJson.php) using a POST request to update the variables.json file. Error handling is implemented to log any errors in the console.

1
2
3
4
5
6
7
8
Copy code
const updatedData = JSON.stringify(jsonData, null, 2);
fetch('updateJson.php', {
    method: 'POST',
    body: updatedData,
})
.then(response => response.json())
.catch(error => console.error('Error Updating JSON:', error));

PHP: updateJson.php

The PHP file receives JSON data through a POST request, decodes it, and updates the variables.json file. It responds with success or error messages, providing appropriate status codes.

1
2
3
4
5
6
7
8
// ... (Check if JSON data is present, decode JSON data)

$filePath = 'variables.json';
file_put_contents($filePath, json_encode($decodedData, JSON_PRETTY_PRINT));

header('Content-Type: application/json');
echo json_encode(['status' => 'success']);
// ... (Error handling for decoding and empty JSON data)

Reset Values

Purpose

The Reset Values function is designed to reset input fields to default values based on the Defaultvariables.json file.

JavaScript Function: ResetValues()

The function fetches Defaultvariables.json, extracts values, and updates the corresponding input fields.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function ResetValues(){
    var screenWidth = document.getElementById("width");
    var screenHeight = document.getElementById("height");

    fetch('Defaultvariables.json')
        .then(response => response.json())
        .then(jsonData => {
            screenWidth.value = jsonData.screen.width;
            screenHeight.value = jsonData.screen.height;
        })
        .catch(error => console.error('Error loading JSON:', error));
}
This function can be associated with a button click or any other triggering event to reset input values to defaults.

Flask Web Application with MQTT Integration

Overview

The provided Python code represents a Flask web application designed for controlling carts, configuring broker settings, and managing camera settings. The application utilizes the Paho MQTT client library for MQTT communication and incorporates custom modules and scripts for combined server and camera functionality.

Dependencies

sys: Provides access to system-specific parameters and functions. paho.mqtt.client: The MQTT client library for handling MQTT communication. json: Facilitates JSON encoding and decoding. combinedServerAndCamera: A custom module that includes functionality for sending JSON messages (send_json_message) and running the camera (main). logging: A module for configuring and utilizing logging within the application. Flask: A lightweight web framework for building web applications in Python. subprocess: Enables the creation and management of additional processes. os: Provides a way to interact with the operating system, used for handling file paths.

Flask Web Application Initialization

Create Flask App: Initializes a Flask web application instance.

1
app = Flask(__name__)
Retrieve Directory Path: Determines the directory where app.py is located to construct the absolute path to variables.json.
1
2
current_dir = os.path.dirname(os.path.abspath(__file__))
json_file_path = os.path.join(current_dir, 'static', 'json', 'variables.json')
Read variables.json: Opens and reads the variables.json file, extracting MQTT connection details.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
with open(json_file_path) as f:
    jsonData = json.load(f)

mqttSubjectName = jsonData["Message"]
mqttName = jsonData["mqttConnection"]["broker"]
mqttPort = jsonData["mqttConnection"]["port"]
mqttAlive = jsonData["mqttConnection"]["keepAlive"]
Save to grepper
MQTT Client Setup: Configures and starts the MQTT client.
python
Copy code
client_id = "unique_client_id"
client = mqtt.Client(client_id=client_id)
client.connect(mqttName, mqttPort, mqttAlive)
client.loop_start()

Flask Routes

Main Page ("/")

GET and POST Handling: Handles both GET and POST requests for the main page ("/"). For POST requests, retrieves form data (cartID, distanceID, angleID) and sends a JSON message using the send_json_message function.

1
2
3
4
@app.route('/', methods=["GET", "POST"])
def gfg():
    # ... (Request handling logic)
    return render_template("index.html")

Broker Settings ("/brokerSettings") and Camera Settings ("/cameraSettings")

Render Templates: Renders templates for the broker settings and camera settings pages.

1
2
3
4
5
6
7
8
Copy code
@app.route('/brokerSettings')
def broker_settings():
    return render_template('brokerSettings.html')

@app.route('/cameraSettings')
def camera_settings():
    return render_template('cameraSettings.html')

Update variables.json ("/updateJson")

POST Request Handling: Defines a route for updating variables.json via a POST request. Receives JSON data from the request body, updates the JSON file, and responds with success or error messages.

1
2
3
4
@app.route('/updateJson', methods=['POST'])
def update_json():
    # ... (JSON update logic)
    return render_template("index.html")

Run Camera ("/runCamera")

GET Request Handling: Defines a route for running the camera. Calls the main function from the custom module and renders the camera settings template.

1
2
3
4
@app.route('/runCamera')
def runCamera():
    combinedServerAndCamera.main()
    return render_template('cameraSettings.html')

Flask Application Execution

Run Application: Executes the Flask application when the script is executed directly.

1
2
if __name__ == '__main__':
    app.run()

Summary

This Flask web application provides a user interface for cart control, broker settings, and camera settings. It utilizes the Paho MQTT client library for communication, includes custom modules for additional functionality, and follows a modular structure with distinct routes for different functionalities. The application is designed to be executed as a standalone script, showcasing a combination of web and IoT functionalities.