middle term text

zyp
zyp 1 week ago
parent 0aac17f2cb
commit 08cf1dea0d

@ -70,7 +70,7 @@ def gen_frames(): # generate frame by frame from camera
@app.route('/control/sendit', methods=['POST']) @app.route('/control/sendit', methods=['POST'])
def send_command(): def send_command():
# 定义目标 IP 地址、端口和路由 # 定义目标 IP 地址、端口和路由
ip = "192.168.98.204" ip = "192.168.60.204"
port = 3000 port = 3000
route = "sendit2" route = "sendit2"

@ -1,31 +1,46 @@
from flask import Flask, render_template, Response from flask import Flask, request, jsonify
from picamera2 import Picamera2
import time
import cv2 import cv2
import threading
import time
app = Flask(__name__) app = Flask(__name__)
def gen_frames(): # generate frame by frame from camera # 设置存储照片的目录路径
picam2 = Picamera2() photo_path = '/Desktop/cars/photo/'
picam2.configure(picam2.create_video_configuration(main={"format": 'XRGB8888', "size": (640, 480)}))
picam2.start() # 初始化摄像头
while True: camera = cv2.VideoCapture(-1)
# Capture frame-by-frame camera.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
frame = picam2.capture_array() # read the camera frame camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
ret, buffer = cv2.imencode('.jpg', frame) # 初始化变量
frame = buffer.tobytes() photo_num_count = 0
yield (b'--frame\r\n' capture_lock = threading.Lock()
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') # concat frame one by one and show result last_photo_time = time.time()
@app.route('/') # 拍照函数
def index(): def capture_photo():
return render_template('index.html') global photo_num_count
with capture_lock:
@app.route('/video_feed') ret, frame = camera.read()
def video_feed(): if ret:
#Video streaming route. Put this in the src attribute of an img tag photo_num_count += 1
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame') photo_filename = f'{photo_path}photo_{photo_num_count}.jpg'
cv2.imwrite(photo_filename, frame)
print(f'{photo_num_count} photos saved. new photo: {photo_filename}')
# 拍照请求处理
@app.route('/photo', methods=['POST'])
def photo():
capture_photo()
return jsonify({"status": "photo captured"})
# 停止请求处理
@app.route('/stop', methods=['POST'])
def stop():
camera.release()
print("Camera stopped")
return jsonify({"status": "camera stopped"})
if __name__ == '__main__': if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True) app.run(host='0.0.0.0', port=5000)

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

@ -0,0 +1,218 @@
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<link href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="http://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
<meta charset="utf-8">
<title>Live Video Based on Flask</title>
<link rel="stylesheet" href='/style.css'/>
<style type="text/css">
#front {
margin-left: 40px;
margin-bottom: 3px;
}
#rear{
margin-top: 3px;
margin-left: 40px;
}
.btn{
background: #e8080b;
}
</style>
</head>
<body>
<h5>实时视频流</h5>
<img src="{{ url_for('video_feed') }}">
<p> 小车控制界面</p>
<bodylink = "red">
<a href="control" target="_blank">小车控制</a>
<!-- 添加文本传输的输入框和按钮 -->
<div class="form-group">
<label for="inputIp">目标服务器 IP 地址:</label>
<input type="text" class="form-control" id="inputIp" placeholder="输入 IP 地址">
</div>
<div class="form-group">
<label for="inputPort">目标服务器 端口:</label>
<input type="text" class="form-control" id="inputPort" placeholder="输入端口号">
</div>
<div class="form-group">
<label for="inputText">要发送的文本内容:</label>
<textarea class="form-control" id="inputText" rows="3" placeholder="输入文本内容"></textarea>
</div>
<button type="button" class="btn btn-primary" onclick="sendText()">发送文本</button>
<div id="container" class="container">
<div>
<button id="front" type="button" onclick="forward()" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-up" style="margin-left: 56px;"> </button>
</div>
<!-- <div>
<button id="printButton" type="button" onclick="printClicked()" class="btn btn-lg btn-primary">打印点击</button>
</div> -->
<div>
<button type="button" onclick="left()" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-left" > </button>
<button type="button" onclick="stop()" class="btn btn-lg btn-primary glyphicon glyphicon-stop"> </button>
<button type="button" onclick="right()" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-right" > </button>
<!-- ---------------------------------------- -->
<button type="button" onclick="takePhoto()">拍照</button>
<!-- ---------------------------------------- -->
</div>
<button id="rear" type="button" onclick="back()" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-down" style="margin-left: 56px;"> </button>
</div>
</div>
<script src='/Decoder.js'></script>
<script src='/YUVCanvas.js'></script>
<script src='/Player.js'></script>
<script>
// player
window.player = new Player({ useWorker: true, webgl: 'auto', size: { width: 848, height: 480 } })
var playerElement = document.getElementById('viewer')
playerElement.appendChild(window.player.canvas)
// Websocket
var wsUri = window.location.protocol.replace(/http/,'ws')+'//'+window.location.hostname+':9000'
var ws = new WebSocket(wsUri)
ws.binaryType = 'arraybuffer'
ws.onopen = function (e) {
console.log('Client connected')
ws.onmessage = function (msg) {
// decode stream
window.player.decode(new Uint8Array(msg.data));
}
}
ws.onclose = function (e) {
console.log('Client disconnected')
}
</script>
<script>
function printClicked() {
// console.log("132465789891651354684");
}
// ---------------------------------------
function takePhoto() {
window.location.href = "{{ url_for('take_photo') }}"; // 重定向到拍照请求
}
// ---------------------------------------
function forward() {
console.log("132465789891651354684");
$.ajax({
type: "GET",
dataType: "json",
url: "/control/forward" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
}
function back() {
$.ajax({
type: "GET",
dataType: "json",
url: "/control/back" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
} function right() {
$.ajax({
type: "GET",
dataType: "json",
url: "/control/right" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
} function left() {
$.ajax({
type: "GET",
dataType: "json",
url: "/control/left" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
} function stop() {
$.ajax({
type: "GET",
dataType: "json",
url: "/control/stop" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
}
</script>
<script>
function refreshPage() {
location.reload(); // 刷新页面
}
// 发送文本
function sendText() {
const ip = document.getElementById('inputIp').value;
const port = document.getElementById('inputPort').value;
const text = document.getElementById('inputText').value;
// 使用fetch API发送POST请求
fetch('/send_text', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `ip=${ip}&port=${port}&text=${encodeURIComponent(text)}`
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
</script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>

@ -0,0 +1,171 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# appCam.py
# based on tutorial ==> https://blog.miguelgrinberg.com/post/video-streaming-with-flask
# PiCam Local Web Server with Flask
# MJRoBot.org 19Jan18
from flask import Flask, render_template, Response, redirect, url_for, send_file, jsonify, request
# Raspberry Pi camera module (requires picamera package)
#from camera_pi import Camera
from picamera2 import Picamera2
import os
import time
from gevent import pywsgi
from car import CAR
#from PiCamera_H264_Server import stream
import threading
import cv2
app = Flask(__name__, static_url_path='')
# 照片保存路径
PHOTO_PATH = "photo.jpg"
def gen_frames(): # generate frame by frame from camera
picam2 = Picamera2()
picam2.configure(picam2.create_video_configuration(main={"format": 'XRGB8888', "size": (640, 480)}))
picam2.start()
while True:
# Capture frame-by-frame
frame = picam2.capture_array() # read the camera frame
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') # concat frame one by one and show result
@app.route('/')
def index():
return render_template('index-t.html')
@app.route('/video_feed')
def video_feed():
#Video streaming route. Put this in the src attribute of an img tag
return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
#---------------------------------------------------------------------------------
@app.route('/take_photo')
def take_photo():
picam2 = Picamera2()
picam2.configure(picam2.create_video_configuration(main={"format": 'XRGB8888', "size": (640, 480)}))
picam2.start()
frame = picam2.capture_array() # Capture a single frame
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
cv2.imwrite(PHOTO_PATH, frame) # Save the frame as a JPEG file
return send_file(PHOTO_PATH, as_attachment=True) # Send the file to download
#---------------------------------------------------------------------------------------
# def gen(camera):
# """Video streaming generator function."""
# while True:
# frame = camera.get_frame()
# yield (b'--frame\r\n'
# b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
# @app.route('/capture')
# def capture():
# pic = open("qrcode.png", "wb")
# frame = Camera().get_frame()
# pic.write(frame)
# return Response(b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n',
# mimetype='multipart/x-mixed-replace; boundary=frame')
# #return send_file("qrcode.png", mimetype='image/png')
# #return redirect(url_for('index'))
# @app.route('/video_feed')
# def video_feed():
# """Video streaming route. Put this in the src attribute of an img tag."""
# return Response(gen(Camera()),
# mimetype='multipart/x-mixed-replace; boundary=frame')
car = CAR()
@app.route('/control/')
def control_index():
word = """指令:\n
/stop(/Q): 小车停止运动\n
/forward(/W): 小车开始运动\n
/back(/S): 小车向后运动\n
/left(/A): 小车向左运动\n
/right(/D): 小车向右运动\n"""
print(word)
return word
# def execute_forward_function():
# url = "http://192.168.185.242:80/send_command" # 示例URL实际使用时需要替换为正确的服务器地址
# data = {"command": 'base -c {"T":1,"L":0.5,"R":0.5}'} # 请求体数据
# # 发送请求并打印返回结果
# try:
# response = request.post(url, data=data)
# print(response.text) # 打印服务器返回的内容
# except request.exceptions.RequestException as e:
# print(f"请求发生错误: {e}")
# print("执行前进功能")
# # 返回一些结果
# return "前进功能已执行"
# @app.route('/control/forward', methods=['GET'])
# def control_forward():
# try:
# # 获取前端发送的数据
# data = request.args
# # 调试输出接收到的数据
# print("接收到的数据:", data)
# # 执行你的函数
# result = execute_forward_function() # 确保这个函数是可以被调用的,如果有必要打印它的返回值
# # 返回JSON响应, result 需要确保是可json化的对象
# return jsonify({
# "resultCode": 200,
# "message": "请求成功",
# "data": result
# })
# except Exception as e:
# print(f"发生错误: {e}") # 打印异常
# return jsonify({"resultCode": 500, "message": "内部服务器错误"}), 500 # 返回500错误
@app.route('/control/<path:info>')
def fun(info):
if hasattr(car, info):
getattr(car, info)()
return 'Run: '+info+'\n'
else:
return 'Error: '+info+' not be defined\n'
# 新增路由处理文本传输功能
@app.route('/send_text', methods=['POST'])
def send_text():
try:
# 获取前端发送的数据
data = request.form
ip = data.get('ip')
port = int(data.get('port'))
text = data.get('text')
# 构建URL
url = "http://{}:{}/send_text".format(ip, port)
# 发送请求
response = requests.post(url, data={'text': text})
# 返回响应
return jsonify({
"resultCode": 200,
"message": "请求成功",
"data": response.text
})
except Exception as e:
print(f"error: {e}")
return jsonify({"resultCode": 500, "message": "内部服务器错误"}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port =80, debug=True, threaded=True)
# t = threading.Thread(target=stream)
# t.start()
# server = pywsgi.WSGIServer(('0.0.0.0', 80), app)
# server.serve_forever()

@ -0,0 +1,218 @@
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<link href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="http://cdn.staticfile.org/jquery/2.2.4/jquery.min.js"></script>
<meta charset="utf-8">
<title>Live Video Based on Flask</title>
<link rel="stylesheet" href='/style.css'/>
<style type="text/css">
#front {
margin-left: 40px;
margin-bottom: 3px;
}
#rear{
margin-top: 3px;
margin-left: 40px;
}
.btn{
background: #e8080b;
}
</style>
</head>
<body>
<h5>实时视频流</h5>
<img src="{{ url_for('video_feed') }}">
<p> 小车控制界面</p>
<bodylink = "red">
<a href="control" target="_blank">小车控制</a>
<!-- 添加文本传输的输入框和按钮 -->
<div class="form-group">
<label for="inputIp">目标服务器 IP 地址:</label>
<input type="text" class="form-control" id="inputIp" placeholder="输入 IP 地址">
</div>
<div class="form-group">
<label for="inputPort">目标服务器 端口:</label>
<input type="text" class="form-control" id="inputPort" placeholder="输入端口号">
</div>
<div class="form-group">
<label for="inputText">要发送的文本内容:</label>
<textarea class="form-control" id="inputText" rows="3" placeholder="输入文本内容"></textarea>
</div>
<button type="button" class="btn btn-primary" onclick="sendText()">发送文本</button>
<div id="container" class="container">
<div>
<button id="front" type="button" onclick="forward()" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-up" style="margin-left: 56px;"> </button>
</div>
<!-- <div>
<button id="printButton" type="button" onclick="printClicked()" class="btn btn-lg btn-primary">打印点击</button>
</div> -->
<div>
<button type="button" onclick="left()" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-left" > </button>
<button type="button" onclick="stop()" class="btn btn-lg btn-primary glyphicon glyphicon-stop"> </button>
<button type="button" onclick="right()" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-right" > </button>
<!-- ---------------------------------------- -->
<button type="button" onclick="takePhoto()">拍照</button>
<!-- ---------------------------------------- -->
</div>
<button id="rear" type="button" onclick="back()" class="btn btn-lg btn-primary glyphicon glyphicon-circle-arrow-down" style="margin-left: 56px;"> </button>
</div>
</div>
<script src='/Decoder.js'></script>
<script src='/YUVCanvas.js'></script>
<script src='/Player.js'></script>
<script>
// player
window.player = new Player({ useWorker: true, webgl: 'auto', size: { width: 848, height: 480 } })
var playerElement = document.getElementById('viewer')
playerElement.appendChild(window.player.canvas)
// Websocket
var wsUri = window.location.protocol.replace(/http/,'ws')+'//'+window.location.hostname+':9000'
var ws = new WebSocket(wsUri)
ws.binaryType = 'arraybuffer'
ws.onopen = function (e) {
console.log('Client connected')
ws.onmessage = function (msg) {
// decode stream
window.player.decode(new Uint8Array(msg.data));
}
}
ws.onclose = function (e) {
console.log('Client disconnected')
}
</script>
<script>
function printClicked() {
// console.log("132465789891651354684");
}
// ---------------------------------------
function takePhoto() {
window.location.href = "{{ url_for('take_photo') }}"; // 重定向到拍照请求
}
// ---------------------------------------
function forward() {
console.log("132465789891651354684");
$.ajax({
type: "GET",
dataType: "json",
url: "/control/forward" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
}
function back() {
$.ajax({
type: "GET",
dataType: "json",
url: "/control/back" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
} function right() {
$.ajax({
type: "GET",
dataType: "json",
url: "/control/right" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
} function left() {
$.ajax({
type: "GET",
dataType: "json",
url: "/control/left" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
} function stop() {
$.ajax({
type: "GET",
dataType: "json",
url: "/control/stop" ,
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
}
;
},
error : function() {
}
});
}
</script>
<script>
function refreshPage() {
location.reload(); // 刷新页面
}
// 发送文本
function sendText() {
const ip = document.getElementById('inputIp').value;
const port = document.getElementById('inputPort').value;
const text = document.getElementById('inputText').value;
// 使用fetch API发送POST请求
fetch('/send_text', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `ip=${ip}&port=${port}&text=${encodeURIComponent(text)}`
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
}
</script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
Loading…
Cancel
Save