树莓派通过TCP发送读取的传感器信息,通过UDP发送摄像头信息,采用opencv编码,通过两个线程来分别实现这两个功能,TCP线程如下:
def tcplink(sock, addr):
pow=30
#print('Accept new connection from %s:%s...' % addr)
try:
while True:
temp=str(pow)
sock.send(temp.encode('gbk'))
pow=pow+10
time.sleep(0.5)
if pow>100:
pow=0
#print(data)
except Exception as e:
sock.close()
在TCP连接时获取其IP地址再用于UDP的数据发送,这样可以不用修改输入客户端的ip地址。UDP线程如下:
def udpsend(addr):
HOST = addr[0] #'192.168.1.15'
PORT = 9090
WIDTH = 1280
HEIGHT = 720
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket对象
server.connect((HOST, PORT))
capture = cv2.VideoCapture(0) # VideoCapture对象,可获取摄像头设备的数据
capture.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT)
try:
while True:
success, frame = capture.read()
while not success and frame is None:
success, frame = capture.read() # 获取视频帧
result, imgencode = cv2.imencode('.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 65]) # 编码
# server.sendall(struct.pack('i',imgencode.shape[0])) #发送编码后的字节长度,这个值不是固定的
server.sendall(imgencode)
except Exception as e:
print(e)
# server.sendall(struct.pack('c',1)) #发送关闭消息
capture.release()
server.close()