Skip to content

Web Code

Camera tuning Page

As a way of changing variables in a user-friendly way we have the camera tuning page. The primary function of this page is to input variables and send those variables into JSON format, and update the variables.json

The html mostly consists of input fields with the number type (here given a small part of the forms) with labels specified for their indipendent id (which will be important when importing in the javascript) and there is a submit button that starts the javascript function described below

HTML

 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

Start of the function UpdateCamera this function first collects all the values that have been inputted on the fields based on their unique ID's

1
2
3
function UpdateCamera() {
    //Set variables to the input fields values (Red)
    var RedHueUpper = document.getElementById("RedHueUpper").value;
it then Fetches the variables.json file that's included in the web folder and conferts the response into JsonData Then jsonData gets updated if any of the values isn't null or "" It also parses the values using ParseInt, to turn the variables into numbers instead of strings as the input fields are set to number it should only be sending number values

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    //Get the variables.json file
    fetch('variables.json')
        //get a json response
        .then(response => response.json())
        .then(jsonData => {
        //This updates the received json data to the variables from the input field if it was filled.
        //Red Upper
            //Hue
            if(RedHueUpper != null && RedHueUpper != "")
            jsonData.colorValues.red.upperValue.hue = parseInt(RedHueUpper)
        //Debug code
        console.log(jsonData);
it does this for all color variables and then sends a debug log to the web console, for the developer to check if the code is right

It then converts the data back into JSON format (due to it being turned into a variable) It then fetches the php file to send it a post request with the JSON data. Which then has some error prevention implemented. it also gets another response in json in order to avoid errors.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
         // Convert the modified object back to JSON
         const updatedData = JSON.stringify(jsonData, null, 2);
         //fetch the php file and send over the jsondata trough httpPOST
         fetch('updateJson.php', {
            method: 'POST',
            body: updatedData,
        })
        //Get another json response
        .then(response => response.json())
        //if an error is found log that error in the console
        .catch(error => console.error('Error Updating JSON:', error));
    })
    //if an error is found log that error in the console
    .catch(error => console.error('Error loading JSON:', error))

}
The updateBroker() functions the same way with the broker variables

php

The php file takes Json files as Post request and updates the Variable.json file it firsts sets the incoming json file as variable. if the jsondata isn't empty than it decodes the incoming information into json if that goes trough normally it then grabs the variables.json file trough it's path then turns the incoming json data into the variables file then gives the client a response of success. if anything goes wrong you gain a bad request response.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php
// Get the JSON data from the request body
$jsonData = file_get_contents("php://input");

// Check if JSON data is present
if (!empty($jsonData)) {
    // Decode JSON data
    $decodedData = json_decode($jsonData, true);

    // Check if JSON decoding was successful
    if ($decodedData !== null) {
        // Set the path to variables.json
        $filePath = 'variables.json';

        // Update the JSON file with the submitted data
        file_put_contents($filePath, json_encode($decodedData, JSON_PRETTY_PRINT));

        // Respond to the client
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success']);
    } else {
        // Respond with an error message if JSON decoding fails
        header('HTTP/1.1 400 Bad Request');
        echo json_encode(['status' => 'error', 'message' => 'Invalid JSON data']);
    }
} else {
    // Respond with an error message if JSON data is not present
    header('HTTP/1.1 400 Bad Request');
    echo json_encode(['status' => 'error', 'message' => 'No JSON data provided']);
}
?>

Reset Values

It's a fairly simple code that takes the input fields and changes the value variable for the html fields, to the values from the Default variables json.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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))
}

Webpage code

The webpage we use runs with flask we use flask so we are able to execute python scripts with the webpage.

The presented Python code constitutes a Flask web application geared towards cart control. Employing Flask, a lightweight web framework, the application features three distinct routes: "/" for cart control, "/brokerSettings" for configuring broker settings, and "/cameraSettings" for camera settings.

In the primary route "/", the application handles both GET and POST requests. For POST requests, it retrieves data from an HTML form containing inputs named cartID, distanceID, and angleID. The data undergoes conversion to integers and is then passed to the send_json_message function. This function presumably sends a JSON message to control the specified cart based on the received parameters.

The route concludes by rendering the index.html template, which likely contains the user interface for cart control commands. Additionally, two other routes, "/brokerSettings" and "/cameraSettings", render templates for configuring broker and camera settings, respectively.

The navigation bar in the HTML file provides links for easy access to the three pages. This separation of concerns enhances the clarity and organization of the web application, following best practices in web development. Overall, the Flask application offers a simple and functional interface for interactive cart control and configuration.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
@app.route('/', methods =["GET", "POST"])
def gfg():
    if request.method == "POST":
       # getting input with name = fname in HTML form
       cart = request.form.get("cartID")
       # getting input with name = lname in HTML form 
       distance = request.form.get("distanceID") 
       angle = request.form.get("angleID")

       cart_int = int(cart) 
       distance_int = int(distance)
       angle_int = int(angle)
       send_json_message(client= client, cart= cart_int, distance= distance_int, angle= angle_int )
    return render_template("index.html")

@app.route('/brokerSettings')
def broker_settings():
    return render_template('brokerSettings.html')

@app.route('/cameraSettings')
def camera_settings():
    return render_template('cameraSettings.html')
1
2
3
4
5
<nav>
            <a href="/"><p>Control carts</p></a>
            <a href="/brokerSettings"><p>Broker settings</p></a>
            <a href="/cameraSettings"><p>Camera settings</p></a>
        </nav>

Webpage additions

Trough development there has been two new routes added, updateJson and RunCamera.

updateJson

This is a flask variant of the original php script. Due to us using flask for our web application as it meshes well with our use of python, the original php code had to be replaced by flask as it wasn't allowing it to get post request normally and it would've caused extra round-about efforts to make the php still do it's function when flask could do the same.

The Code functions like php where it takes the request as json and then overwrites variables.json afterwards it just routes back to the index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# Define route for updating variables.json via POST request
@app.route('/updateJson', methods=['POST'])
def update_json():
    try:
        # Get JSON data from the request body
        json_data = request.get_json()

        # Check if JSON data is present
        if json_data:
            # Set the path to variables.json
            file_path = 'variables.json'

            # Update the JSON file with the submitted data
            with open(file_path, 'w') as file:
                json.dump(json_data, file, indent=2)

            return render_template("index.html")

    except Exception as e:
        # Respond with an error message if an exception occurs
        return jsonify({'status': 'error', 'message': str(e)}), 500

runCamera

This route and function acts for a button press that runs the main script. combinedServerAndCamera is this projects python script that starts the camera detection aswell as the mqtt connection, The buttons purpose is so that you can edit the json on the original settings page and see your changes.

1
2
3
4
5
# Define route for running the camera
@app.route('/runCamera')
def runCamera():
    combinedServerAndCamera.main()
    return render_template('cameraSettings.html')
1
<a class="button" href="/runCamera">Run</a>