一、服务器
(1)简单讲解
C/S结构实现控制,树莓派运行服务器,中断通过访问网页实现控制小车,使用UDP通信。其中使用多线程控制小车的自动避障功能,写的不好的地方请批评指正。
(2)代码实现
创建server.py
from http.server import BaseHTTPRequestHandler,HTTPServer
import time
import socket
import urllib
from carCtrl import CAR
from camera_control import Camera
from threading import Thread
global loop
global direction
loop =True
class CarServer(BaseHTTPRequestHandler):
carControl = CAR()
cameraControler = Camera()
i=0
def get_host_ip(self):
'''
This method is used for getting local ip address
The car server will deploy on this ip
'''
try:
serverSocket = socket.socket(socket.AF_INET
,socket.SOCK_DGRAM)
serverSocket.connect(("192.168.0.12",80))
localIP = serverSocket.getsockname()[0]
finally:
return localIP
def do_GET(self):
'''
Define the car control GUI for client
For the first deition, it will only return direction control GUI
'''
localIP = CarServer.get_host_ip(self)
#when this GET method is called,then should init the car
self.carControl.reset()
#read control page html file from control.html
controlPageFile = open("control.html")
controlPageGUI = controlPageFile.read()
controlPageFile.close()
controlPageGUI = controlPageGUI.replace(
"requestAddress","http://"+ localIP +":9090/")
controlPageGUI = controlPageGUI.replace(
"cameraAddress","http://"+ localIP +":8080/")
self.send_response(200)
self.send_header("Content-type","text/html")
self.end_headers()
self.wfile.write(controlPageGUI.encode())
def do_POST(self):
length = int(self.headers['Content-Length'])
qs = self.rfile.read(length)
global direction
direction = 'S'
direction = qs.decode()
print(direction)
cameraDirection = ['HR','HL','VU','VD','GL','GF','GR','GU','GD','RESET']
if direction in cameraDirection:
#control camera
self.cameraControler.cameraRotation(direction)
elif direction =="Auto":
if self.i == 0: