import cv2 as cv import io import logging import socketserver from threading import Condition from threading import Thread from http import server import time import traceback import socket import os from urllib.parse import urlparse from Tank import Tank class StreamingHandler(server.BaseHTTPRequestHandler): def do_GET(self): # 摄像头 if self.path.startswith('/camera'): self.send_response(200) self.send_header('Age', 0) self.send_header('Cache-Control', 'no-cache, private') self.send_header('Pragma', 'no-cache') self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME') self.end_headers() ltime=0 try: while True: self.wfile.write(b'--FRAME\r\n') self.send_header('Content-Type', 'image/jpeg') ret, deal_frame = cap.read() deal_frame = cv.flip(deal_frame, -1) r, show_frame = cv.imencode('.jpg', deal_frame) self.send_header('Content-Length', len(show_frame)) self.end_headers() self.wfile.write(bytearray(show_frame)) self.wfile.write(b'\r\n') except Exception as e: logging.warning( 'Removed streaming client %s: %s', self.client_address, str(e)) traceback.print_exc() # 坦克控制 elif self.path.startswith('/control'): parsed_result=urlparse(self.path) command = parsed_result.query print(command) # 解析命令 orders = command.split('=') ord = orders[0] value = orders[1] print(value) print('{0} = {1}'.format(ord,value)) if ord=='direct': if value=='forward': tank.forward() elif value=='backward': tank.backward() elif value=='left': tank.left() elif value=='right': tank.right() elif value=='stop': tank.stop() elif ord=='speed': speed=int(value) tank.setSpeed(speed) self.send_response(200) self.send_header('Content-type', 'text/html') self.send_header("test", "This is test!") self.end_headers() self.wfile.write(b'success') else: self.send_error(404) self.end_headers() class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer): #添加ipv6的支持 address_family = socket.AF_INET6 allow_reuse_address = True daemon_threads = True def run(port = 8080): global cap, server, tank tank = Tank() # tank.setSpeed(30) cap = cv.VideoCapture(0) cap.set(cv.CAP_PROP_FRAME_WIDTH, 1280) cap.set(cv.CAP_PROP_FRAME_HEIGHT, 720) try: address = ('', port) server = StreamingServer(address, StreamingHandler) server.serve_forever() except Exception as e: traceback.print_exc() finally: cap.release() def stop(): global server server.shutdown() server.server_close() run()