Im using RaspberryPI and USB camera to make mini raspberry pi project, but when click start Camera button in web, I got GET http://localhost:8080/null 404 (Not Found) error. Here are codes from my project, but I think one of delivery.html, mqttio.js, mqtt.py is wrong. I’ve really been looking at the code for over 6 hours, but I really don’t know how to fix this. What should I do?
templates/delivery.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>mini project</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.2/mqttws31.min.js" type="text/javascript"></script>
<script src="./static/mqttio.js" type="text/javascript"></script>
<script src="./static/image.js" type="text/javascript"></script>
<script>
window.addEventListener("load", function () {
var url = new String(document.location);
ip = (url.split("//"))[1]; // ip = "224...:8080/"
ip = (ip.split(":"))[0]; // ip = "224..."
document.getElementById("broker").value = ip
});
</script>
<style>
canvas {background-color:lightblue}
</style>
</head>
<body>
<h3>camera</h3>
<hr>
<form id="connection-form">
<b>broker IP:</b>
<input id="broker" type="text" name="broker" value=""><br>
<b>port : 9001</b><br>
<input type="button" onclick="startConnect()" value="Connect">
<input type="button" onclick="startDisconnect()" value="Disconnect">
</form>
<hr>
<h3>get image(topic:image)</h3>
<hr>
<form id="subscribe-form">
<input type="button" onclick="startCamera()" value="start camera">
<input type="button" onclick="stopCamera()" value="stop camera">
</form>
<canvas id="myCanvas" width="320" height="240"></canvas>
<hr>
<h3>Led (topic:led)</h3>
<hr>
<form id="LED-control-form">
<label>on <input type="radio" name="led" value="1" onchange="publish('led', this.value)"></label>
<label>off <input type="radio" name="led" value="0" checked onchange="publish('led', this.value)"><br><br></label>
</form>
<hr>
<h3>get temperature(topic:temperature)</h3>
<hr>
<form id="subscribe-form">
<input type="button" onclick="subscribe('temperature')" value="start">
<input type="button" onclick="unsubscribe('temperature')" value="stop">
</form>
<h3>get distance(topic:ultrasonic)</h3>
<hr>
<form id="subscribe-form">
<input type="button" onclick="subscribe('ultrasonic')" value="start">
<input type="button" onclick="unsubscribe('ultrasonic')" value="stop">
</form>
<div id="messages"></div>
</body>
</html>
static/mqttio.js
var port = 9001
var client = null;
function startConnect() {
clientID = "clientID-" + parseInt(Math.random() * 100);
broker = document.getElementById("broker").value;
client = new Paho.MQTT.Client(broker, Number(port), clientID);
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.connect({
onSuccess: onConnect,
});
}
var isConnected = false;
function onConnect() {
isConnected = true;
document.getElementById("messages").innerHTML += '<span>Connected</span><br/>';
}
var topicSave;
function subscribe(topic) {
if(client == null) return;
if(isConnected != true) {
topicSave = topic;
window.setTimeout("subscribe(topicSave)", 500);
return
}
document.getElementById("messages").innerHTML += '<span>Subscribing to: ' + topic + '</span><br/>';
client.subscribe(topic);
}
function publish(topic, msg) {
if(client == null) return;
client.send(topic, msg, 0, false);
}
function unsubscribe(topic) {
if(client == null || isConnected != true) return;
document.getElementById("messages").innerHTML += '<span>Unsubscribing to: ' + topic + '</span><br/>';
client.unsubscribe(topic, null);
}
function onConnectionLost(responseObject) {
document.getElementById("messages").innerHTML += '<span>error</span><br/>';
if (responseObject.errorCode !== 0) {
document.getElementById("messages").innerHTML += '<span>error : ' + + responseObject.errorMessage + '</span><br/>';
}
}
function onMessageArrived(msg) {
console.log("onMessageArrived: " + msg.payloadString);
if(msg.destinationName == "image") {
console.log("received")
drawImage(msg.payloadBytes);
}
document.getElementById("messages").innerHTML += '<span>topic : ' + msg.destinationName + ' | ' + msg.payloadString + '</span><br/>';
}
function startDisconnect() {
client.disconnect();
document.getElementById("messages").innerHTML += '<span>Disconnected</span><br/>';
}
mqtt.py
import io, time
import cv2
from PIL import Image, ImageFilter
import paho.mqtt.client as mqtt
import camera
import base64
import temp
import circuit
isStart = False
def on_connect(client, userdata, msg, rc):
client.subscribe("camera")
def on_message(client, userdata, msg):
global isStart
if msg.payload.decode('utf-8') == 'start':
isStart = True
print("Start Camera")
else:
isStart = False
pass
def on_connect(client, userdata, flag, rc):
client.subscribe("led", qos=0)
def on_message(client, userdata, msg):
on_off = int(msg.payload)
circuit.controlLED(on_off)
broker_ip = "localhost"
client = mqtt.Client()
client.connect(broker_ip, 1883)
client.on_connect = on_connect
client.on_message = on_message
client.loop_start()
camera.init()
stream = io.BytesIO()
while True:
if isStart == True:
frame = camera.take_picture()
stream.seek(0)
image = Image.fromarray(frame)
image.save(stream, format='JPEG')
client.publish("image", stream.getvalue(), qos=0)
stream.truncate()
else:
print("I am idle")
time.sleep(1)
distance = circuit.measure_distance()
temperature = temp.get_temperature(temp.sensor)
client.publish("ultrasonic", distance, qos=0)
client.publish("temperature", temperature, qos=0)
time.sleep(1)
camera.release()
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT']=0
@app.route('/')
def index():
return render_template('delivery.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True)
circuitpy
import time
import RPi.GPIO as GPIO
def controlLED(on_off):
GPIO.output(led, on_off)
def measure_distance():
GPIO.output(trig, 1)
GPIO.output(trig, 0)
while(GPIO.input(echo) == 0):
pass
pulse_start = time.time()
while(GPIO.input(echo) == 1):
pass
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
return pulse_duration*340*100/2
trig = 20 # GPIO20
echo = 16 # GPIO16
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(trig, GPIO.OUT)
GPIO.setup(echo, GPIO.IN)
led = 6 # GPIO6
led = 5
GPIO.setup(led, GPIO.OUT) # GPIO6
GPIO.setup(led, GPIO.OUT) # GPIO5
temp.py
import time
import RPi.GPIO as GPIO
from adafruit_htu21d import HTU21D
import busio
def get_temperature(sensor):
return float(sensor.temperature)
def get_humidity(sensor):
return float(sensor.relative_humidity)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
sda = 2
scl = 3
i2c = busio.I2C(scl, sda)
sensor = HTU21D(i2c)
def read_sensor_data():
while True:
temperature = get_temperature(sensor)
humidity = get_humidity(sensor)
print("temperature is %4.1f" % temperature)
print("humidity is %4.1f %%" % humidity)
time.sleep(1)
if __name__ == '__main__':
read_sensor_data()
camera.py
import sys
import time
import cv2
camera = None
def init(camera_id=0, width=640, height=480, buffer_size=1):
global camera
camera = cv2.VideoCapture(camera_id, cv2.CAP_V4L)
camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
camera.set(cv2.CAP_PROP_BUFFERSIZE, buffer_size)
def take_picture(most_recent=False):
global camera
len = 0 if most_recent == False else camera.get(cv2.CAP_PROP_BUFFERSIZE)
while(len > 0):
camera.grab()
len -= 1
success, image = camera.read()
if not success:
return None
return image
def final():
if camera != None:
camera.release()
camera = None
static/image.js
var canvas;
var context;
var img;
window.addEventListener("load", function() {
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
img = new Image();
img.onload = function () {
context.drawImage(img, 0, 0, canvas.width, canvas.height);
}
});
function bytes2base64( bytes ) {
var binary = '';
var bytes = new Uint8Array( bytes );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
function drawImage(bytes) {
img.src = "data:image/jpg;base64," + bytes2base64(bytes);
}
var isImageSubscribed = false;
function startCamera() {
if(!isImageSubscribed) {
subscribe('image');
isImageSubscribed = true;
}
publish('camera', 'start');
img.src = null
}
function stopCamera() {
if(!isImageSubscribed) {
unsubscribe('image');
isImageSubscribed = true;
}
publish('camera', 'stop');
}
The code using led, ultrasonic sensor, and temperature sensor works fine, but only USB camera is a problem, so I looked at all the related codes, but I couldn’t find any answers.