### Initialize Car to Run Mode using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API initializes the camera and turning wheels to start the car in run mode. It is accessed via an HTTP GET request to the '/runmode' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/runmode
```
--------------------------------
### Install Python 2.7 (Windows)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/README.md
Instructions for downloading and installing Python version 2.7.11, which is a prerequisite for running certain calibration client scripts on Windows.
```bash
https://www.python.org/downloads/release/python-2711/
```
--------------------------------
### Install Django with Pip
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/README.md
Installs the Django framework using pip, a Python package installer. This is a prerequisite for running the HTML server.
```bash
sudo pip install django
```
--------------------------------
### Initialize Car to Calibration Mode using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API initializes the camera and turning wheels to start the car in calibration mode. It is accessed via an HTTP GET request to the '/calibrationmode' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/calibrationmode
```
--------------------------------
### GPL Interactive Program Notice Example
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer-experimental/www/LICENSE.txt
An example of a short notice that an interactive program should display upon startup. It includes version information, copyright, warranty disclaimer, and how to access license details.
```text
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
```
--------------------------------
### Get Calibration Configuration using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API retrieves the current calibration configuration from the server. It is accessed via an HTTP GET request to the '/calibrate/getconfig' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/calibrate/getconfig
```
--------------------------------
### Copyright Disclaimer Example
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer-experimental/www/LICENSE.txt
A sample copyright disclaimer that an employer or institution might sign to disclaim copyright interest in a program. This example is for a hypothetical program named 'Gnomovision'.
```text
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
, 1 April 1989
Ty Coon, President of Vice
```
--------------------------------
### Confirm and Save Calibration using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API confirms and saves the current calibration configuration. It is accessed via an HTTP GET request to the '/calibrate/confirm' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/calibrate/confirm
```
--------------------------------
### GNU GPL Copyright Notice Example
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer-experimental/www/LICENSE.txt
This is a template for including the GNU General Public License (GPL) copyright notice in your source files. It should include the program's name, year, author, and a statement about its free software status under the GPL.
```text
Copyright (C)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
```
--------------------------------
### Run Django Development Server
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/README.md
Starts the Django development server on a Raspberry Pi. This command should be executed within the http_server directory of the project. It makes the server accessible on the local network.
```bash
sudo python manage.py runserver 0.0.0.0:8000
```
--------------------------------
### Reset Camera to Home Position using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API resets the camera's pan and tilt servos to their home position. It is accessed via an HTTP GET request to the '/camera/home' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/camera/home
```
--------------------------------
### Set Motor to Run Forward in Calibration Mode using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API sets the motor to run forward while in calibration mode. It is accessed via an HTTP GET request to the '/calibrate/motor/run' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/calibrate/motor/run
```
--------------------------------
### Stop Motor using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API stops the motor of the smart car. It is accessed via an HTTP GET request to the '/motor/stop' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/motor/stop
```
--------------------------------
### Reverse Left Motor in Calibration Mode using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API reverses the direction of the left motor while in calibration mode. It is accessed via an HTTP GET request to the '/calibrate/motor/left/reverse' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/calibrate/motor/left/reverse
```
--------------------------------
### Control Car Forward using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API controls the smart car to move forward. It is accessed via an HTTP GET request to the specified Raspberry Pi IP address and port, followed by the '/motor/forward' endpoint. No specific programming language is required, as it can be executed directly from a web browser.
```http
GET http://[Raspberry Pi IP address]:8000/motor/forward
```
--------------------------------
### Reverse Right Motor in Calibration Mode using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API reverses the direction of the right motor while in calibration mode. It is accessed via an HTTP GET request to the '/calibrate/motor/right/reverse' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/calibrate/motor/right/reverse
```
--------------------------------
### Stop Motor in Calibration Mode using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API stops the motor while in calibration mode. It is accessed via an HTTP GET request to the '/calibrate/motor/stop' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/calibrate/motor/stop
```
--------------------------------
### Control Car Backward using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API controls the smart car to move backward. It is accessed via an HTTP GET request to the specified Raspberry Pi IP address and port, followed by the '/motor/backward' endpoint. This command can be entered directly into a web browser's address bar.
```http
GET http://[Raspberry Pi IP address]:8000/motor/backward
```
--------------------------------
### Control Camera Tilt Increase using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API increases the tilt servo position on the Y axis, moving the camera up. It is accessed via an HTTP GET request to the '/camera/increase/y' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/camera/increase/y
```
--------------------------------
### JavaScript: Dynamically Generate Input Controls
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/control.htm
This function generates input controls for the smart video car kit based on data loaded from a JSON file. It supports various control types like integer spinboxes, boolean checkboxes, string text fields, dropdown menus, and buttons. It also handles the initial setup of resolution selection. This function is essential for creating the interactive control interface.
```javascript
function addInput(plugin_id) {
$.getJSON("input_"+plugin_id+".json", function(data) {
$.each(data.controls, function(i,item){
$("
").attr("id", "td-status").appendTo("#tr-status");
});
}
/*$.getJSON("input.json", function(data) {
$.each(data.formats, function(i,item){
if (item.current == "true") {
$("")
.attr("id", "select-resolution")
.attr("style", "width: 100%;")
.change(function(){setResolution($(this).val());})
.appendTo("#resolutions");
$.each(item.resolutions, function(val,res){
if (item.currentResolution == val) {
$("#select-resolution").append($('').attr("selected", "selected").val(val).html(res));
} else {
$("#select-resolution").append($('').val(val).html(res));
}
});
}
});
});*/
```
--------------------------------
### Set Motor Speed using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API allows setting the motor speed of the smart car. The speed is passed as a variable in the URL, ranging from 0 to 100. It is accessed via an HTTP GET request to the '/motor/set/speed/[speed]' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/motor/set/speed/[speed]
```
--------------------------------
### Set Tilt Servo Offset in Calibration Mode using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API sets the offset for the tilt servo during calibration. It accepts a sign ('+' or '-') and a value between 0 and 999. Accessed via '/calibrate/tile/[+/-]/[value]'. Note the typo 'tile' in the original documentation.
```http
GET http://[Raspberry Pi IP address]:8000/calibrate/tile/[+/-]/[value]
```
--------------------------------
### Control Camera Pan Decrease using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API decreases the pan servo position on the X axis, moving the camera to the left. It is accessed via an HTTP GET request to the '/camera/decrease/x' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/camera/decrease/x
```
--------------------------------
### Set Steering Angle using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API sets the angle of the turning wheels. The angle is provided as a variable in the URL, ranging from 0 to 255. It is accessed via an HTTP GET request to the '/turning/[angle]' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/turning/[angle]
```
--------------------------------
### Control Camera Tilt Decrease using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API decreases the tilt servo position on the Y axis, moving the camera down. It is accessed via an HTTP GET request to the '/camera/decrease/y' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/camera/decrease/y
```
--------------------------------
### Control Camera Pan Increase using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API increases the pan servo position on the X axis, moving the camera to the right. It is accessed via an HTTP GET request to the '/camera/increase/x' endpoint.
```http
GET http://[Raspberry Pi IP address]:8000/camera/increase/x
```
--------------------------------
### Set Turning Offset in Calibration Mode using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API sets the offset for the turning servos during calibration. It accepts a sign ('+' or '-') and a value between 0 and 999. Accessed via '/calibrate/turning/[+/-]/[value]'.
```http
GET http://[Raspberry Pi IP address]:8000/calibrate/turning/[+/-]/[value]
```
--------------------------------
### Set Pan Servo Offset in Calibration Mode using HTML GET Request
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
This API sets the offset for the pan servo during calibration. It accepts a sign ('+' or '-') and a value between 0 and 999. Accessed via '/calibrate/pan/[+/-]/[value]'.
```http
GET http://[Raspberry Pi IP address]:8000/calibrate/pan/[+/-]/[value]
```
--------------------------------
### JavaScript: Initialize UI Tabs and Load Controls
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/control.htm
This script initializes UI tabs for different input and output sections of the smart video car kit control panel. It dynamically loads control configurations from JSON files and calls `addInput` and `addOutput` functions to populate the respective UI elements. This is the main entry point for setting up the interactive interface.
```javascript
$.getJSON("program.json", function(data) {
$.each(data.inputs, function(i,input){
$("").attr("id", "li_in-"+input.id).appendTo("#ul_tabs");
$("").attr("href", "#controldiv_in-"+input.id)
.text(input.name).appendTo("#li_in-"+input.id);
$("").attr("id", "controldiv_in-"+input.id).appendTo("#tabs");
$("
").attr("id", "controltable_out-"+output.id).appendTo("#controldiv_out-"+output.id);
} )
$.each(data.inputs, function(i,input){
addInput(input.id);
} )
$.each(data.outputs, function(i,output){
addOutput(output.id);
} )
} );
```
--------------------------------
### Run Client Application on Windows
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/README.md
Command to execute the main client application script on a Windows environment. This allows users to control the smart car from their PC.
```bash
client_app.py
```
--------------------------------
### Run Calibration Client on Windows
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/README.md
Command to execute the calibration client script specifically designed for Windows users. This script helps in calibrating the car's movement and camera controls.
```bash
client/cali_client_win.py
```
--------------------------------
### Initialization APIs
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
APIs to initialize the car's modes, such as run mode or calibration mode.
```APIDOC
## GET /runmode
### Description
Initializes the camera and turning wheels to start the run mode.
### Method
GET
### Endpoint
`/runmode`
## GET /calibrationmode
### Description
Initializes the camera and turning wheels to start the calibration mode.
### Method
GET
### Endpoint
`/calibrationmode`
```
--------------------------------
### Initialize Video Stream and Canvas (JavaScript)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer-experimental/www/javascript_motiondetection.html
This function initializes the video streaming by creating an HTML5 canvas element and appending it to the DOM. It then loads the first snapshot image and sets up the 'newPictureComplete' callback to handle subsequent image loading and comparison.
```javascript
/* Initialize the elements
* Create a Canvas() object and insert it into the page
* Download the first image
* Pause the Livestream again if we were paused previously
This way we will not pause, but we will lower the refresh rate
For a proper pause, the page can not be reloaded
*/
function run() {
canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
canvas.id = "comparison_canvas";
document.getElementById("comparison").appendChild(canvas);
img1 = new Image();
img1.onload = newPictureComplete;
img1.src = "/?action=snapshot";
if (window.name.indexOf('paused') != -1) {
play_pause(document.getElementById("stream"));
}
}
```
--------------------------------
### Display Static Snapshot using HTML
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/static.html
This snippet demonstrates how to display a static snapshot from the MJPG-streamer. It uses an HTML image tag with the source URL pointing to the '/?action=snapshot' endpoint, which should work with any browser. No specific client-side dependencies are mentioned.
```html
```
--------------------------------
### Calibration APIs
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
APIs for calibrating the car's components, including motors, servos, and configuration saving.
```APIDOC
## GET /calibrate/getconfig
### Description
Retrieves the current calibration configuration from the server.
### Method
GET
### Endpoint
`/calibrate/getconfig`
## GET /calibrate/motor/run
### Description
Sets the motor to run forward during calibration mode.
### Method
GET
### Endpoint
`/calibrate/motor/run`
## GET /calibrate/motor/stop
### Description
Stops the motor during calibration mode.
### Method
GET
### Endpoint
`/calibrate/motor/stop`
## GET /calibrate/motor/left/reverse
### Description
Reverses the operation of the left motor during calibration.
### Method
GET
### Endpoint
`/calibrate/motor/left/reverse`
## GET /calibrate/motor/right/reverse
### Description
Reverses the operation of the right motor during calibration.
### Method
GET
### Endpoint
`/calibrate/motor/right/reverse`
## GET /calibrate/pan/[+/-]/[value]
### Description
Sets the pan servo offset. Accepts a '+' or '-' sign followed by a value between 0 and 999.
### Method
GET
### Endpoint
`/calibrate/pan/[+/-]/[value]`
### Parameters
#### Path Parameters
- **sign** (string) - Required - Either '+' or '-'.
- **value** (integer) - Required - The offset value (0-999).
## GET /calibrate/tile/[+/-]/[value]
### Description
Sets the tilt servo offset. Accepts a '+' or '-' sign followed by a value between 0 and 999. Note: 'tile' is a typo and refers to the tilt servo.
### Method
GET
### Endpoint
`/calibrate/tile/[+/-]/[value]`
### Parameters
#### Path Parameters
- **sign** (string) - Required - Either '+' or '-'.
- **value** (integer) - Required - The offset value (0-999).
## GET /calibrate/turning/[+/-]/[value]
### Description
Sets the turning offset for the wheels. Accepts a '+' or '-' sign followed by a value between 0 and 999.
### Method
GET
### Endpoint
`/calibrate/turning/[+/-]/[value]`
### Parameters
#### Path Parameters
- **sign** (string) - Required - Either '+' or '-'.
- **value** (integer) - Required - The offset value (0-999).
## GET /calibrate/confirm
### Description
Confirms and saves the calibration configuration.
### Method
GET
### Endpoint
`/calibrate/confirm`
```
--------------------------------
### Run I2C Helper Script (Linux)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/README.md
This command is used to execute the i2cHelper.py script, which assists in resolving I2C communication issues with the Servo Controller on Raspberry Pi. It requires superuser privileges.
```bash
sudo python i2cHelper.py
```
--------------------------------
### Initialize Video Stream and Canvas (JavaScript)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/javascript_motiondetection.html
Initializes the video stream by creating a canvas element and appending it to the 'comparison' div. It then loads the first snapshot image and sets up the 'newPictureComplete' callback. This function also handles resuming the stream if it was previously paused.
```javascript
/* Initialize the elements
* Create a Canvas() object and insert it into the page
* Download the first image
* Pause the Livestream again if we were paused previously
This way we will not pause, but we will lower the refresh rate
For a proper pause, the page can not be reloaded
*/
function run() {
canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
canvas.id = "comparison_canvas";
document.getElementById("comparison").appendChild(canvas);
img1 = new Image();
img1.onload=newPictureComplete;
img1.src = "/?action=snapshot";
if ( window.name.indexOf('paused') != -1 ) {
play_pause(document.getElementById("stream"));
}
}
```
--------------------------------
### Camera Control APIs
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
APIs to control the camera's pan and tilt servos.
```APIDOC
## GET /camera/increase/y
### Description
Increases the Y axis value, moving the tilt servo up.
### Method
GET
### Endpoint
`/camera/increase/y`
## GET /camera/decrease/y
### Description
Decreases the Y axis value, moving the tilt servo down.
### Method
GET
### Endpoint
`/camera/decrease/y`
## GET /camera/increase/x
### Description
Increases the X axis value, moving the pan servo right.
### Method
GET
### Endpoint
`/camera/increase/x`
## GET /camera/decrease/x
### Description
Decreases the X axis value, moving the pan servo left.
### Method
GET
### Endpoint
`/camera/decrease/x`
## GET /camera/home
### Description
Resets the camera position to the "Home" position.
### Method
GET
### Endpoint
`/camera/home`
```
--------------------------------
### Handle New Picture and Update Stream (JavaScript)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/javascript_motiondetection.html
Callback function executed when a new picture is downloaded. It compares the new image ('img1') with the previous one ('img2') using the 'compare' function. Based on the detected movement, it updates visual indicators on the canvas and sends a command to the server if significant motion is detected. It then prepares to load the next image.
```javascript
/* Callback function for completed picture downloads
With every new picture a compare() is performed.
The new picture is 'img1', the previous picture is stored in 'img2'.
*/
function newPictureComplete() {
// just compare if there are two pictures
if ( img2 != null ) {
var res;
try {
// compare the two pictures, the given threshold helps to ignore noise
res = compare(img1, img2, canvas, 50);
} catch(e) {
// errors can happen if the pictures were corrupted during transfer
// instead of giving up, just proceed
}
// show to the user if we regards this as motion
// decide for a color depending on movement (more then N pixels)
// draw into free area of canvas
// (hardcoded positions for better performance)
var ctx = canvas.getContext("2d");
ctx.fillStyle = ( res > 5 ) ? "rgb(200,0,0)" : "rgb(0,200,0)";
ctx.fillRect (0, 50, 25, 50);
ctx.fillRect (75, 50, 25, 50);
// send server our finding that there was some movement
if ( res > 5 ) {
AJAX_get('/?action=command&command=store')
}
}
// copy reference of img1 to img2
img2 = img1;
img2.onload = null; // important to not call newPictureComplete twice
// load a new picture into img1
img1 = new Image();
img1.onload=newPictureComplete;
// load next picture in a few milliseconds
// the server blocks anyway until a fresh picture has arrived, so it can never be faster
// than the framerate. This timeout is intended to have the option
// to lower the required processing power at client side.
window.setTimeout("img1.src='/?action=snapshot&unique='+Math.random();", 1);
}
```
--------------------------------
### Generate MJPG-Streamer Playlist in Javascript
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/videolan.html
This Javascript function generates a data URI for an M3U playlist. It prompts the user to open the playlist with VideoLAN Player and constructs the stream URL based on the current host. It requires a browser with Javascript enabled.
```javascript
function playlist(link, hint) {
var res = true;
if (hint) res = confirm("Please open the following playlist directly with the VideoLAN Player");
if ( !res ) {
link.href = "#";
return false;
}
var m3u = "data:playlist/mjpgstreamer,#EXTM3U%0A%0A#EXTINF:-1,Webcam%20MJPG-Stream%0Ahttp://"+ window.location.host +"/?action=stream";
link.href = m3u;
return true;
}
function run() {
document.getElementById("stream").firstChild.nodeValue = "http://"+ window.location.host +"/?action=stream";
}
```
--------------------------------
### JavaScript Car Control with Keyboard Input
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer-experimental/www/control_old.html
This JavaScript code snippet allows users to control the movement of the SunFounder Smart Video Car using keyboard arrow keys and the spacebar. It sends specific commands to the car via AJAX requests based on key presses. Dependencies include the `AJAX_get` function, which is assumed to be defined elsewhere for handling HTTP requests.
```javascript
function send_command(cmd) { document.getElementById('hints').firstChild.nodeValue = "Send command: " + cmd; AJAX_get('/?action=command&command='+ cmd) }
function AJAX_response(text) { document.getElementById('hints').firstChild.nodeValue = "Got response: " + text; }
function KeyDown(ev) { ev = ev || window.event; pressed = ev.which || ev.keyCode; switch (pressed) { case 37: send_command('pan_plus'); break; case 39: send_command('pan_minus'); break; case 38: send_command('tilt_minus'); break; case 40: send_command('tilt_plus'); break; case 32: send_command('reset_pan_tilt'); break; default: break; } }
document.onkeydown = KeyDown;
```
--------------------------------
### Handle New Picture Completion and Motion Event (JavaScript)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer-experimental/www/javascript_motiondetection.html
This callback function is executed when a new image is loaded. It compares the new image with the previous one using the 'compare' function. If significant motion is detected, it updates the canvas with a color indicator and sends a command to the server.
```javascript
/* Callback function for completed picture downloads
With every new picture a compare() is performed.
The new picture is 'img1', the previous picture is stored in 'img2'.
*/
function newPictureComplete() {
// just compare if there are two pictures
if (img2 != null) {
var res;
try {
// compare the two pictures, the given threshold helps to ignore noise
res = compare(img1, img2, canvas, 50);
} catch (e) {
// errors can happen if the pictures were corrupted during transfer
// instead of giving up, just proceed
}
// show to the user if we regards this as motion
// decide for a color depending on movement (more then N pixels)
// draw into free area of canvas
// (hardcoded positions for better performance)
var ctx = canvas.getContext("2d");
ctx.fillStyle = (res > 5) ? "rgb(200,0,0)" : "rgb(0,200,0)";
ctx.fillRect(0, 50, 25, 50);
ctx.fillRect(75, 50, 25, 50);
// send server our finding that there was some movement
if (res > 5) {
AJAX_get('/?action=command&command=store');
}
}
// copy reference of img1 to img2
img2 = img1;
img2.onload = null; // clear onload for img2
// load a new picture into img1
img1 = new Image();
img1.onload = newPictureComplete;
// load next picture in a few milliseconds
// the server blocks anyway until a fresh picture has arrived, so it can never be faster
// than the framerate. This timeout is intended to have the option
// to lower the required processing power at client side.
window.setTimeout("img1.src='/?action=snapshot&unique=' + Math.random();", 1);
}
```
--------------------------------
### Display MJPG-Streamer Video Stream with Java Applet
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/java.html
This Java applet code snippet demonstrates how to embed and display a video stream from MJPG-Streamer within a web page. It requires a Java-enabled browser and the cambozola.jar library. The 'url' parameter specifies the stream source.
```html
```
--------------------------------
### JavaScript: Control Functions for SunFounder Car Kit
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/control.htm
Provides functions to send commands to the car kit. These functions abstract the AJAX calls to the server, allowing for setting different types of controls like boolean, string, and integer values. Includes basic validation for string inputs.
```javascript
function setControl(dest, plugin, id, group, value) { $.get('/?action=command&dest=' + dest + '&plugin=' + plugin+ '&id='+ id + '&group='+ group + '&value=' + value ); }
function setControl_bool(dest, plugin, id, group, value) { if (value == false) setControl(dest, plugin, id, group, 0); else setControl(dest, plugin, id, group, 1); }
function setControl_string(dest, plugin, id, group, value) { if (value.length < minlength) { alert("The input string has to be least"+minlength+" characters!"); return; } $.get('/?action=command&dest=' + dest + '&plugin=' + plugin+ '&id='+ id + '&group='+ group + '&value=' + value , function(data){ alert("Data Loaded: " + data); }); }
```
--------------------------------
### HTML: Display MJPG-Streamer Video Feed
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/stream.html
This HTML snippet demonstrates how to embed the MJPG-streamer video feed directly into a web page using an image tag. The source URL '?action=stream' indicates that the image content is dynamically generated by the MJPG-streamer application. This method is simple and widely compatible.
```html
```
--------------------------------
### Handle AJAX Response (JavaScript)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/javascript_motiondetection.html
Callback function for handling responses from AJAX commands sent to the server. Currently, it does nothing but serves as a placeholder for future enhancements, such as displaying visual feedback to the user.
```javascript
/* Callback function for AJAX command
input.: text is the response of the server
*/
function AJAX_response(text) {
// nothing to do
// later we might show a little folder symbol or so that dissapears
// after a while
}
```
--------------------------------
### Toggle Play/Pause for Live Preview (JavaScript)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/javascript_motiondetection.html
Toggles the play/pause state of the HTTP-push live preview stream. If the current source is a stream, it switches to a snapshot; otherwise, it attempts to resume the stream. It also includes logic to maintain the play/pause state across page reloads.
```javascript
/* can toggle play/pause of the HTTP-push live preview
input.: 'img' is the Image() object displaying the stream/picture
*/
function play_pause(img) {
if ( img.src.indexOf('/?action=stream') != -1 ) {
img.src = "/?action=snapshot&unique="+Math.random();
// to keep the play/pause state over a page reload
// t
```
--------------------------------
### Javascript for MJPG-Streamer Video Feed
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer-experimental/www/javascript.html
This Javascript code is designed to display a live video stream from MJPG-Streamer. It handles image loading, frame rate calculation, and stream pausing. Dependencies include an HTML structure with elements for 'webcam', 'info', 'ravgfps', and 'ravgms'. It dynamically creates and manages image layers to avoid flicker and calculates average frame times and FPS.
```javascript
var imageNr = 0; // Serial number of current image
var finished = new Array(); // References to img objects which have finished downloading
var paused = false;
var previous_time = new Date();
var fNi = 0, msAvg = 0, fpsAvg = 0, fcnt = 0, fN = 80, msa = [], wsize = 4;
function createImageLayer() {
var img = new Image();
img.style.position = "absolute";
img.style.zIndex = -1;
img.onload = imageOnload;
img.onclick = imageOnclick;
img.width = 512;
img.height = 384;
img.src = "/?action=snapshot&n=" + (++imageNr);
var webcam = document.getElementById("webcam");
window.info = document.getElementById('info').firstChild;
window.ravgFps = document.getElementById('ravgfps').firstChild;
window.ravgMs = document.getElementById('ravgms').firstChild;
webcam.insertBefore(img, webcam.firstChild);
document.getElementById('fN').firstChild.nodeValue = fN;
}
function runningAvgs (delta) {
// delta is the measured frame period
var len;
if (fcnt < fN) {
fcnt++; // we need to populate the sample array
msa.push(delta); // calculate average period so far
msAvg += (delta - msAvg) / fcnt;
} else {
/* running average (fN samples) according to the formula: rAvg = rAvg - value_fN_samples_back / fN + newest_value / fN */
msAvg += (delta - msa[0])/fN; // drop oldest ms value, msa[0]
msa = msa.slice(1); // append newest value, delta
msa.push(delta);
}
// calculate average fps
fpsAvg = 1000 / msAvg;
/* once every fN frames, check if we need to adjust the averaging window since faster rates seem to need more samples to reach a stable(er) readout */
if (++fNi == fN) {
fNi = 0;
// new window size
fN = parseInt(fpsAvg * wsize);
len = fcnt - fN; // if our sample array, msa, has extra samples, then trim it to the new size
if (len > 0) {
// adjust averaging window (nr of samples)
msa = msa.splice(len); // avoid populating the sample array again
fcnt = fN;
}
}
}
// Two layers are always present (except at the very beginning), to avoid flicker
function imageOnload() {
this.style.zIndex = imageNr; // Image finished, bring to front!
while (1 < finished.length) {
var del = finished.shift(); // Delete old image(s) from document
del.parentNode.removeChild(del);
}
finished.push(this);
current_time = new Date();
delta = current_time.getTime() - previous_time.getTime();
fps = (1000.0 / delta).toFixed(1);
runningAvgs(delta);
info.nodeValue = delta + " ms (" + fps + " fps)";
ravgFps.nodeValue = fpsAvg.toFixed(1);
ravgMs.nodeValue = msAvg.toFixed(0);
previous_time = current_time;
if (!paused) createImageLayer();
}
function imageOnclick() {
// Clicking on the image will pause the stream
paused = !paused;
if (!paused) createImageLayer();
}
```
--------------------------------
### Steering Control APIs
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/html_server/APIs.md
APIs to control the steering (turning wheels) of the car.
```APIDOC
## GET /turning/[angle]
### Description
Turns the wheels to a specified angle. The angle ranges from 0 to 255, controlling left and right turns.
### Method
GET
### Endpoint
`/turning/[angle]`
### Parameters
#### Path Parameters
- **angle** (integer) - Required - The angle to turn the wheels (0-255).
```
--------------------------------
### Toggle Play/Pause for Live Preview (JavaScript)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer-experimental/www/javascript_motiondetection.html
This function allows toggling between a live stream and snapshot mode for the video preview. It changes the 'src' attribute of the image element to either the stream URL or a new snapshot URL with a unique parameter to ensure a fresh image is loaded.
```javascript
/* can toggle play/pause of the HTTP-push live preview
input.: 'img' is the Image() object displaying the stream/picture
*/
function play_pause(img) {
if (img.src.indexOf('/?action=stream') != -1) {
img.src = "/?action=snapshot&unique=" + Math.random(); // to keep the play/pause state over a page reload
// t
```
--------------------------------
### JavaScript: Dynamically Generate Output Controls
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/control.htm
This function generates output controls for the smart video car kit, similar to input controls. It reads configuration from a JSON file and creates UI elements for various control types. This is used for displaying and potentially interacting with the kit's outputs.
```javascript
function addOutput(plugin_id) {
$.getJSON("output_"+plugin_id+".json", function(data) {
$.each(data.controls, function(i,item){
$("
").attr("id", "tr_"+item.group+"-"+item.id).appendTo("#controltable_out-"+plugin_id);
if (item.type == 4) {
$("
").appendTo("#tr-"+item.id);
} else {
if (item.type == 6) {
$("
").attr("id", "td-status").appendTo("#tr-status");
});
}
```
--------------------------------
### Manage Streaming State with JavaScript
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/mjpg-streamer/mjpg-streamer/www/javascript_motiondetection.html
This JavaScript code snippet manages the streaming state of the video car kit. It checks the current image source and updates the window name to 'streaming' or 'paused' accordingly. This uses the browser's window.name property to persist state across reloads, though cookies or server-side scripting are suggested as cleaner alternatives.
```javascript
if (img.src.indexOf("/?action=stream") !== -1) {
img.src = "/?action=stream";
window.name = 'paused';
} else {
img.src = "/?action=stream";
window.name = 'streaming';
}
```
--------------------------------
### Running Tkinter GUI Client on Raspberry Pi (Python)
Source: https://github.com/sunfounder/sunfounder_smart_video_car_kit_for_raspberrypi/blob/master/README.md
This snippet demonstrates the typical Tkinter initialization that leads to a _tkinter.TclError when executed remotely without a display. The error occurs because Tkinter requires a graphical environment (a DISPLAY variable) which is typically absent in SSH or remote command-line sessions.
```python
from Tkinter import Tk
top = Tk() # Create a top window
# ... rest of the GUI code
```